有没有人知道我该如何用c#.net逐行读取excel数据。用excel数据逐行读取c#.net
我发现了这个代码,它将返回excel中的数据并显示在c#.net的grindview中。我如何才能在服务器端逐行读取数据呢?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
using System.IO;
namespace site
{
public partial class pgTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnImport_Click(object sender, EventArgs e)
{
string connString = "";
string strFileType = Path.GetExtension(fileuploadExcel.FileName).ToLower();
string path = fileuploadExcel.PostedFile.FileName;
//Connection String to Excel Workbook
if (strFileType.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
string query = "SELECT [username],[age],[phone] FROM [Sheet1$]";
OleDbConnection conn = new OleDbConnection(connString);
if (conn.State == ConnectionState.Closed)
conn.Open();
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
grvExcelData.DataSource = ds.Tables[0];
grvExcelData.DataBind();
da.Dispose();
conn.Close();
conn.Dispose();
}
}
}
此代码将做;只是不要将数据绑定到“grvExcelData”(我想这必须对Grid视图执行一些操作)。或者更好;你可以使用Microsoft.Office.Interop.Excel API – aquaraga 2013-04-23 04:00:01
这段代码提供你想要的数据集,不是吗? – 2013-04-23 04:03:41
我相信他只是想检查如何逐行读取excel文件,而不是读取整个excel文件并将其值加载到网格。 – 2013-04-23 04:08:24