【发布时间】:2013-06-11 10:30:14
【问题描述】:
大家好,不使用OLEDB可以加载excel数据吗,我已经为.xls and .xlsx编写了如下的连接字符串代码
ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pFilePath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pFilePath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
在我的系统中,12.0 相关的dll 不存在,我遇到了错误。所以我想知道是否有任何方法可以实现我的要求而不是一般方法
编写的示例代码
public void Method(string pFilePath)
{
DataTable dt = new DataTable();
using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(pFilePath, false))
{
WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
string relationshipId = sheets.First().Id.Value;
WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);
Worksheet workSheet = worksheetPart.Worksheet;
SheetData sheetData = workSheet.GetFirstChild<SheetData>();
IEnumerable<Row> rows = sheetData.Descendants<Row>();
foreach (Cell cell in rows.ElementAt(0))
{
dt.Columns.Add(GetCellValue(spreadSheetDocument, cell));
}
foreach (Row row in rows)
{
DataRow tempRow = dt.NewRow();
for (int i = 0; i < row.Descendants<Cell>().Count(); i++)
{
tempRow[i] = GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i - 1));
}
dt.Rows.Add(tempRow);
}
}
dt.Rows.RemoveAt(0);
}
public static string GetCellValue(SpreadsheetDocument document, Cell cell)
{
SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart;
string value = cell.CellValue.InnerXml;
if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
{
return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
}
else
{
return value;
}
}
但是在foreach (Row row in rows) 这种情况下,我得到了Specified argument was out of the range of valid values.
Parameter name: index 的异常
【问题讨论】:
-
您可以尝试使用OpenXML方法
http://msdn.microsoft.com/en-us/library/office/gg575571.aspx -
嗨
pratik你能告诉我如何加载2003excel 文件,它也需要 2007 年或 2010 年 -
这是使用 OpenXml 方法的限制。 :( 唯一的替代方法是答案中建议的其他第三方工具。
-
在上面的代码中,日期列读取为数字,例如2014 年 1 月读作 41640。您对此有何建议?