我有这个代码上传excel文件并将其放在gridview中:
protected void save_Click(object sender, EventArgs e)
{
try
{
string filename = Path.GetFileName(excelfileupload.FileName);
excelfileupload.SaveAs(Server.MapPath("~/Uploader/") + filename);
err.Text = "Upload status: File uploaded!";
DataTable dt = getDataTableFromExcel(Server.MapPath("~/Uploader/") + filename);
}
catch (Exception ex)
{
err.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
private 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;
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;
}
}
每件事都可以正常工作但是在上传文件.xls时它给了我一个错误:
Upload status: The file could not be uploaded. The following error occured: Can not open the package. Package is an OLE compound document. If this is an encrypted package, please supply the password
不知道它的意思,但是当它尝试将其转换为.xlsx时,它的工作正常而没有错误
如何解决?
答案 0 :(得分:0)
如何解决?
不要使用XLS文件或不要使用EPPlus。
Create advanced Excel 2007/2010 spreadsheets on the server
EPPlus是一个.net库,使用Open Office Xml格式(xlsx)读取和写入 Excel 2007/2010文件
如果您需要打开XLS文件use JET or ACE。