无法使用closedxml读取保存为xls的excel表

时间:2017-01-19 13:06:08

标签: excel asp.net-mvc-5 closedxml

我有以下代码将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时出现错误消息为“无效文件签名”。 任何帮助将受到高度赞赏。

1 个答案:

答案 0 :(得分:0)

ClosedXML生成.xlsx个文件,而不是.xls个文件。

检查您的代码:

Response.AddHeader("content-disposition", "attachment;filename= "+fileName + ".xls");