文檔文件用NPOI插件, 在有導出.xlsx文件時,在打開時總報:html
錯誤提示: Excel在「春天Excel2007.xlsx」中發現不可讀取內容。是否恢復工做簿的內容?若是信任此工做簿的來源,請單擊「是」。 單擊「是」後:Excel 已完成文件級驗證和修復。此工做簿的某些部分可能已被修復或丟棄.bash
處理Excel200七、2010文件,格式.xlsx文件存在一個問題,在調用 Write方法以後關閉了傳入的文件流
spa
//文件流傳入內存
var ms = MemoryStream();
//ms.Length;//會拋出不可讀異常
var fileSize = file.ToArray().Length;//改用複製代碼
問題如何處理呢?直接上代碼以下:
插件
因爲 使用MemoryStream 這個有問題,先改用 FileStreamcode
public void CreateExcelV2(List<work_order> list, Dictionary<string, string> cols, string FileType, string FileName)
{
string path = MapPath("~/Files");
if (Directory.Exists(path) == false) Directory.CreateDirectory(path);
string savePath = path + "/" + FileName + ".xlsx";
try
{
var workbook = new XSSFWorkbook();//2007版本 xlsx
//var workbook = new HSSFWorkbook();
#region 建立生成表格文件.xlsx
var sheet = workbook.CreateSheet("Sheet1");
//key 鍵 自定義寬度
var regNum = new Regex(@"\d+");
//寫入列名
var row = sheet.CreateRow(0);
int i = 0;
foreach (var col in cols.Values)
{
row.CreateCell(i++).SetCellValue(col);
}
//寫入數據
i = 0;
foreach (var item in list)
{
row = sheet.CreateRow(i + 1);
int j = 0;
foreach (var key in cols.Keys)
{
row.CreateCell(j++).SetCellValue(getModelKeyValue(key, item));
}
i++;
}
#endregion
#region 寫出表格文件,下載
Response.Clear();
Response.Charset = "UTF-8";
Response.ContentEncoding = Encoding.GetEncoding("UTF-8");
Response.Buffer = true;
Response.ContentType = FileType;
//調用這個後會關於文件流,在HSSFWorkbook不會關閉因此在處理時應注意
using (var fs = new FileStream(savePath, FileMode.Create, FileAccess.Write))
{
workbook.Write(fs);
fs.Close();
}
using (var fs = new FileStream(savePath, FileMode.Open, FileAccess.Read))
{
long fileSize = fs.Length;
byte[] fileBuffer = new byte[fileSize];
fs.Read(fileBuffer, 0, (int)fileSize);
Response.AddHeader("Content-Length", fileSize.ToString());
Response.AddHeader("Content-Disposition", string.Format("attachment;filename=\"{0}.xlsx\"", HttpUtility.UrlEncode(FileName, Encoding.UTF8)));
Response.BinaryWrite(fileBuffer);
Context.ApplicationInstance.CompleteRequest();
Response.Output.Flush();
fs.Close();
}
/*
using (var file = new MemoryStream())
{
workbook.Write(file);
//加上設置大小下載下來的.xlsx文件打開時纔不會報「Excel 已完成文件級驗證和修復。此工做簿的某些部分可能已被修復或丟棄」
Response.AddHeader("Content-Length", (file.ToArray().Length).ToString());
Response.AddHeader("Content-Disposition", string.Format("attachment;filename=\"{0}.xlsx\"", HttpUtility.UrlEncode(FileName, Encoding.UTF8)));
Response.BinaryWrite(file.GetBuffer());
Context.ApplicationInstance.CompleteRequest();
Response.Output.Flush();
//Response.Flush();
file.Flush();
file.Close();
}
*/
#endregion
}
catch (Exception ex)
{
Response.Write("400, file download excetion. "+ex.Message);
}
finally
{
if (File.Exists(savePath))
{
File.Delete(savePath);
}
Response.End();//不能夠放在try 內,會拋出異常
}
}
複製代碼
參考來源:orm
https://www.cnblogs.com/kaiwanlin/p/5782834.html
htm