[英]Excel c#.net retrieving data without opening excel in the background
I am trying to read a data in an excel sheet using C#, here is my code. 我正在尝试使用C#读取excel工作表中的数据,这是我的代码。
public void ReadExcel()
{
try
{
string sheetName = "Sheet1$A1:C6";
DataTable sheetTable = loadSingleSheet(@"C:\Users\..\Desktop\Sample.xls", sheetName);
}
catch (Exception e)
{
throw e;
}
}
private OleDbConnection returnConnection(string fileName)
{
return new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + "; Jet OLEDB:Engine Type=5;Extended Properties=\"Excel 8.0;\"");
}
private DataTable loadSingleSheet(string fileName, string sheetName)
{
DataTable sheetData = new DataTable();
using (OleDbConnection conn = this.returnConnection(fileName))
{
conn.Open();
// retrieve the data using data adapter
OleDbDataAdapter sheetAdapter = new OleDbDataAdapter("select * from [" + sheetName + "]", conn);
sheetAdapter.Fill(sheetData);
}
return sheetData;
}
But DataTable always get null value 但是DataTable总是获得空值
Here it is how to do it using ODBC and ADO.Net 这是使用ODBC和ADO.Net的方法
private void Form1_Load(object sender, EventArgs e)
{
try
{
string sheetName = "Sheet1$";// Read the whole excel sheet document
DataTable sheetTable = loadSingleSheet(@"C:\excelFile.xls", sheetName);
dataGridView1.DataSource = sheetTable;
string sheetNameWithRange = "Sheet1$A1:D10"; // Read excel sheet document from A1 cell to D10 cell values.
DataTable sheetTableWithRange = loadSingleSheet(@"C:\excelFile.xls",sheetNameWithRange);
dataGridView2.DataSource = sheetTableWithRange;
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message, "");
}
}
private OleDbConnection returnConnection(string fileName)
{
return new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + "; Jet OLEDB:Engine Type=5;Extended Properties=\"Excel 8.0;\"");
}
private DataTable loadSingleSheet(string fileName, string sheetName)
{
DataTable sheetData = new DataTable();
using (OleDbConnection conn = this.returnConnection(fileName))
{
conn.Open();
// retrieve the data using data adapter
OleDbDataAdapter sheetAdapter = new OleDbDataAdapter("select * from [" + sheetName + "]", conn);
sheetAdapter.Fill(sheetData);
}
return sheetData;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.