Excel表格中有三列:
当我尝试从Excel获取数据时,如果工作表在012-231564
列中包含PhoneNo
类型的数据,则生成的DataSet包含空白单元格
var connString = string.Format("Provider=Microsoft.Jet.OleDb.4.0;
Data Source={0};Extended Properties=\"Text;HDR=YES;FMT=Delimited\"",
Path.GetDirectoryName(Server.MapPath("~/DataMiningFiles/" + StrFileName)));
var query = "SELECT * FROM [" + Path.GetFileName(Server.MapPath("~/DataMiningFiles/" + StrFileName)) + "]";
using (var adapter = new OleDbDataAdapter(query, conn)) {
var ObjGetExcelData = new DataSet("CSV File");
adapter.Fill(ObjGetExcelData);
}
答案 0 :(得分:0)
我有很多改变这个tbh。所以,让我们看看......
一般情况下我会逐桌阅读此表。我不熟悉您将该批次读入DataSet的尝试。如果我在新的一年里感到无聊,我可能会有所作为。然而,这个例子将起作用......
string sConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=e:\\Test.xlsx;" +
"Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\"";
OleDbConnection oConnection = new OleDbConnection();
oConnection.ConnectionString = sConnectionString;
oConnection.Open();
//Find all readable Named Ranges and Worksheets
DataTable ExcelSheetNames = oConnection.GetSchema("Tables");
foreach (DataRow SheetNameRow in ExcelSheetNames.Rows)
{
string SheetName = (string)SheetNameRow["Table_Name"];
//Only handle WorkSheets. Named Ranges are otherwise named.
if (SheetName.EndsWith("$") | SheetName.EndsWith("$'"))
{
DataTable SheetContents = new DataTable();
//Read the contents of the sheet into a DataTable
using (OleDbCommand oCmd = new OleDbCommand("Select * From [" + SheetName + "]", oConnection))
{
SheetContents.Load(oCmd.ExecuteReader());
}
//You can also put the DataTable load on one line (I do)
//SheetContents.Load(new OleDbCommand("Select * From [" + SheetName + "]", oConnection).ExecuteReader());
//Print the content of cells A2..C2 to the console window
Console.WriteLine(SheetContents.Rows[0].ItemArray[0]);
Console.WriteLine(SheetContents.Rows[0].ItemArray[1]);
Console.WriteLine(SheetContents.Rows[0].ItemArray[2]);
}
}
oConnection.Close();
顺便提一下,请尽量避免使用" var"变量。强力打字,你以后会为自己和别人留下更多心痛。
如果您知道要阅读的工作表的名称,可以将其全部编码为...
string sConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=e:\\Test.xlsx;" +
"Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\"";
OleDbConnection oConnection = new OleDbConnection();
oConnection.ConnectionString = sConnectionString;
oConnection.Open();
DataTable SheetContents = new DataTable();
SheetContents.Load(new OleDbCommand("Select * From [Sheet1$]", oConnection).ExecuteReader());
Console.WriteLine(SheetContents.Rows[0].ItemArray[0]);
Console.WriteLine(SheetContents.Rows[0].ItemArray[1]);
Console.WriteLine(SheetContents.Rows[0].ItemArray[2]);
oConnection.Close();