我只想使用NPOI SXSSF方法流式处理xlsx文件。但是当我在打开下载流式Excel文件时弹出消息:
Excel在“ MyExcelFile.xlsx”中发现了不可读的内容。你想要_____吗 恢复工作簿的内容?如果您相信这个来源 工作簿,单击是。
我的代码:
Response.Headers.Add("Content-disposition", "attachment; filename=\"MyExce.xlsx\"");
Response.Headers.Add("Content-type", "octet-stream");
SXSSFWorkbook wb = new SXSSFWorkbook();
SXSSFSheet sheet = (SXSSFSheet)wb.CreateSheet("FirstSheet");
IRow row = sheet.CreateRow(0);
ICell cell = row.CreateCell(0);
cell.SetCellValue("firstCell");
//Write file to output stream
wb.Write(Response.Body);
wb.Close();
Response.Body.Flush();
我在做什么错了?
答案 0 :(得分:1)
对于wb.Write
,它将在Response.Body
和public void DownloadFile()
{
MemoryStream ms = new MemoryStream();
using (MemoryStream stream = new MemoryStream())
{
Response.Headers.Add("Content-disposition", "attachment; filename=\"MyExce.xlsx\"");
Response.Headers.Add("Content-type", "octet-stream");
SXSSFWorkbook wb = new SXSSFWorkbook();
SXSSFSheet sheet = (SXSSFSheet)wb.CreateSheet("FirstSheet");
IRow row = sheet.CreateRow(0);
ICell cell = row.CreateCell(0);
cell.SetCellValue("firstCell");
//Write file to output stream
wb.Write(stream);
var byteArray = stream.ToArray();
ms.Write(byteArray, 0, byteArray.Length);
ms.Seek(0, SeekOrigin.Begin);
ms.WriteTo(Response.Body);
}
}
被破坏之后处置流。
请尝试以下代码,以保存流并将保存的流写入正文。
$str = 'Scale Lengths
4 string model - E A D G
5 string model - B E A D G
6 string model - B E A D G C
B
37″';
// We split your string by lines.
$lines = explode("\n", $str);
// We filter this new array by sub array base on regex pattern.
$findedPattern = array_filter($lines, function($line) {
// if is empty line, just ignore it.
if(empty($line))
return false;
// We match all string who start by number, then followed b "string model - " and finally finish by letter and space.
return preg_match('/^\d+ string model \- [A-Z\s]+\s+$/', $line);
});