我使用 Epplus 从流中读取 xlsx 文件。
它有一个错误,它无法读取我的工作簿中的某些列。如何在没有 epplus 的情况下将 xlsx 文件从流读取到数据表?
我的旧代码:
public static DataSet ReadExcelFile(Stream stream)
{
try
{
//2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
IExcelDataReader excelReader =
ExcelReaderFactory.CreateOpenXmlReader(stream);
//...
DataSet result = excelReader.AsDataSet();
return result;
}
catch (Exception x)
{
throw x;
}
}
我没有报告它,但我尝试了很多组合。如果工作表中有空列,epplus reader 无法正确读取列值。
最佳答案
"It has a bug , it cant read some columns in my workbook"
你能描述一下这个bug吗,你有吗reported它还是已经知道,您使用的是什么版本?
这是将 excel 文件加载到
DataTable
的简单方法。与 EPPlus。public static DataTable getDataTableFromExcel(string path)
{
using (var pck = new OfficeOpenXml.ExcelPackage())
{
using (var stream = File.OpenRead(path))
{
pck.Load(stream);
}
var ws = pck.Workbook.Worksheets.First();
DataTable tbl = new DataTable();
bool hasHeader = true; // adjust it accordingly( i've mentioned that this is a simple approach)
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 (var rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
{
var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
var row = tbl.NewRow();
foreach (var cell in wsRow)
{
row[cell.Start.Column - 1] = cell.Text;
}
tbl.Rows.Add(row);
}
return tbl;
}
}
关于asp.net - 如何将流excel文件转换为数据表C#?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11239805/