使用.net 4.5
我试图使用EPPlus(v4.0.4)读取.xls / .xlsx文件,但收到错误。 SO对同一错误有疑问,但没有任何关联或解决我的问题。
issuetype = {'name' : 'Bug'}
错误发生在protected void Page_Load(object sender, EventArgs e)
{
GetDataTableFromExcel(@"D:\test.xlsx");
}
private DataTable GetDataTableFromExcel(string path, bool hasHeader = true)
{
using (var pck = new OfficeOpenXml.ExcelPackage())
{
using (var stream = File.OpenRead(path))
{
pck.Load(stream);
}
var ws = pck.Workbook.Worksheets[1];
DataTable tbl = new DataTable();
foreach (var firstRowCell in ws.Cells[1, 1, 1, ws.Dimension.End.Column])
{
tbl.Columns.Add(hasHeader ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column));
}
var startRow = hasHeader ? 2 : 1;
for (int rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
{
var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
DataRow row = tbl.Rows.Add();
foreach (var cell in wsRow)
{
row[cell.Start.Column - 1] = cell.Text;
}
}
return tbl;
}
}
写入操作期间发生磁盘错误。 (例外 HRESULT:0x8003001D(STG_E_WRITEFAULT)
答案 0 :(得分:1)
我们首先可以使用Microsoft.Office.Introp.excel将xls文件转换为xlsx格式,然后在转换后使用新格式的文件通过EPPPLUS进行读取。
public static DataTable ReadExcelFileToDataTable(string filePath, bool isFirstRowHeader = true)
{
#region Convert xls file to xlsx file
// Convert xls file to xlsx file --to use below code Microsoft.Excel must installed on the system on which cod eis running
var app = new Microsoft.Office.Interop.Excel.Application();
var web = app.Workbooks.Open("");
web.SaveAs(filePath + ".x", FileFormat: Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook);
web.Close();
app.Quit();
#endregion
var newFileName = filePath + ".x";
DataTable tbl = new DataTable(); ;
Excel.ExcelPackage xlsPackage = new Excel.ExcelPackage(new FileInfo(newFileName)); //using Excel = OfficeOpenXml; <--EPPLUS
Excel.ExcelWorkbook workBook = xlsPackage.Workbook;
try
{
Excel.ExcelWorksheet wsworkSheet = workBook.Worksheets[0];
foreach (var firstRowCell in wsworkSheet.Cells[1, 1, 1, wsworkSheet.Dimension.End.Column])
{
var colName = "";
colName = firstRowCell.Text;
tbl.Columns.Add(isFirstRowHeader ? colName : string.Format("Column {0}", firstRowCell.Start.Column));
}
var startRow = isFirstRowHeader ? 2 : 1;
for (int rowNum = startRow; rowNum <= wsworkSheet.Dimension.End.Row; rowNum++)
{
var wsRow = wsworkSheet.Cells[rowNum, 1, rowNum, wsworkSheet.Dimension.End.Column];
DataRow row = tbl.Rows.Add();
foreach (var cell in wsRow)
{
row[cell.Start.Column - 1] = cell.Text;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return tbl;
}