用excel数据逐行读取c#.net
问题描述:
有没有人知道我该如何用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();
}
}
}
答
您可以使用OleDbDataReader
如下
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
var val1= reader[0].ToString();
}
reader.Close();
}
答
由于Excel适用于范围,您应该首先获取您希望读取的单元格范围。之后,您现在可以使用for循环浏览它们。你可以看到下面的例子:
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\myexcel.xlsx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
MessageBox.Show(xlRange.Cells[i, j].Value2.ToString());
}
}
这个代码块更详细的解释可以发现here。
+1
Lem,你可以请更新你提供的链接...它不工作了...谢谢 – nick 2016-05-03 04:14:30
+0
链接目前是404。 – bunkerdive 2018-01-05 07:35:51
此代码将做;只是不要将数据绑定到“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