我有以下代码将excel表格中的数据保存为.xls
public ActionResult ExportToExcel()
{
DataTable tbl = CopyGenericToDataTable(res);
tbl.TableName = "InvalidInvoices";
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(tbl);
wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
wb.Style.Font.Bold = true;
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename= "+fileName + ".xls");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
以上是在客户端下载xls excel表的代码。它工作正常,数据保存在Excel工作表中。 问题是我是否尝试使用以下代码上传此相同文件 -
if (files != null)
{
HttpPostedFileBase upload = files.FirstOrDefault();
Stream stream = upload.InputStream;
DataSet result = new DataSet();
if (upload != null && upload.ContentLength > 0)
{
if (upload.FileName.EndsWith(".xls") || upload.FileName.EndsWith(".xlsx"))
{
// ExcelDataReader works with the binary Excel file, so it needs a FileStream
// to get started. This is how we avoid dependencies on ACE or Interop:
// We return the interface, so that
IExcelDataReader reader = null;
if (upload.FileName.EndsWith(".xls"))
{
reader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else if (upload.FileName.EndsWith(".xlsx"))
{
reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
reader.IsFirstRowAsColumnNames = false;
result = reader.AsDataSet();
reader.Close();
}
}
}
在上面的代码中,我在ExcelReaderFactory.CreateBinaryReader(stream)中收到错误; 在流中,它具有以字节为单位的值,仅使用excelreaderfactory读取器的createBinaryreader时出现错误消息为“无效文件签名”。 任何帮助将受到高度赞赏。
答案 0 :(得分:0)
ClosedXML
生成.xlsx
个文件,而不是.xls
个文件。
检查您的代码:
Response.AddHeader("content-disposition", "attachment;filename= "+fileName + ".xls");