我有一個WPF應用程序,我有功能從Excel中讀取數據。 我這樣做使用OLEDB,它工作得很好,直到我發現有255的列限制和數據將被截斷,除非數據> 255個字符不存在於前八行。解決此問題的方法是更新註冊表,這意味着更新所有用戶的註冊表。所以我不想這樣做。使用OLEDB從Excel導入數據時截斷數據,有哪些替代方法?
OLEDB代碼:
string strSQL = "SELECT * FROM [Sheet1$]";
OleDbCommand cmd = new OleDbCommand(strSQL, conn);
DataSet ds1 = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds1);
作爲替代方案,我試圖Interop.Excel。但是,OLEDB似乎比較慢。使用Interop.Excel需要花費2秒鐘的Excel工作表約需15秒鐘。
System.Data.DataTable tempTable = new System.Data.DataTable();
tempTable.TableName = "ResultData";
Excel.Application app = new Excel.Application();
Excel.Workbook book = null;
Excel.Range range = null;
try
{
app.Visible = false;
app.ScreenUpdating = false;
app.DisplayAlerts = false;
book = app.Workbooks.Open(inputFilePath, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value);
foreach (Excel.Worksheet sheet in book.Worksheets)
{
Logger.LogException("Values for Sheet " + sheet.Index, System.Reflection.MethodBase.GetCurrentMethod().ToString());
// get a range to work with
range = sheet.get_Range("A1", Missing.Value);
// get the end of values to the right (will stop at the first empty cell)
range = range.get_End(Excel.XlDirection.xlToRight);
// get the end of values toward the bottom, looking in the last column (will stop at first empty cell)
range = range.get_End(Excel.XlDirection.xlDown);
// get the address of the bottom, right cell
string downAddress = range.get_Address(
false, false, Excel.XlReferenceStyle.xlA1,
Type.Missing, Type.Missing);
// Get the range, then values from a1
range = sheet.get_Range("A1", downAddress);
object[,] values = (object[,])range.Value2;
//Get the Column Names
for (int k = 0; k < values.GetLength(1);)
{
tempTable.Columns.Add(Convert.ToString(values[1, ++k]).Trim());
}
for (int i = 2; i <= values.GetLength(0); i++)//first row contains the column names, so start from the next row.
{
System.Data.DataRow dr = tempTable.NewRow();
for (int j = 1; j <= values.GetLength(1); j++)//columns
{
dr[j - 1] = values[i, j];
}
tempTable.Rows.Add(dr);
}
}
是否有另一種方法與OLEDB一樣快?
列表和行不固定在Excel工作表中。
你處理'xls'文件或'xlsx'文件? –
您可以使用ACE是Microsoft Office驅動程序。 Oledb帶有窗戶,而ACE配有辦公室。我想你可以在沒有辦公室許可證的情況下安裝ACE,但我從來沒有成功完成它。你只需要改變連接字符串。請參閱www.connectionstrings.com。 – jdweng
@ScottChamberlain它是xlsx文件 – perplexedDev