//异常提示:ICSharpCode.SharpZipLib.Zip.ZipException: EOF in header NPOIMemoryStream stream = new NPOIMemoryStream(); using (var fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite)) { fileStream.CopyTo(stream); stream.Position = 0; //这一句不加就会上面的异常错误 } IWorkbook wk = new NPOI.XSSF.UserModel.XSSFWorkbook(stream);
还有种情况报这个错误,NPOI打开了空的流对象,这种情况NPOI不用传流对象创建IWorkbook对象,直接调用无参构造函数,最后操作完之后将结果写入到流中;最后提示一下:写入流之前也需要 stream.Position = 0;
protected IWorkbook GetWorkbook(string ext) { IWorkbook book = null; if (ext.ToLower().Equals(".xls")) { book = new HSSFWorkbook(); } else if (ext.ToLower().Equals(".xlsx")) { book = new NPOI.XSSF.UserModel.XSSFWorkbook(); } else { throw new SinoException("只支持Excel文件"); } return book; }
打开Excel文件流的方式
protected IWorkbook OpenWorkbook(Stream stream, string ext) { IWorkbook book = null; if (ext.ToLower().Equals(".xls")) { book = new HSSFWorkbook(stream); } else if (ext.ToLower().Equals(".xlsx")) { book = new NPOI.XSSF.UserModel.XSSFWorkbook(stream); } else { throw new SinoException("只支持Excel文件"); } return book; }
public class NPOIMemoryStream : MemoryStream { /// <summary> /// 获取流是否关闭 /// </summary> public bool IsColse { get; private set; } public NPOIMemoryStream(bool colse = false) { IsColse = colse; } public override void Close() { if (IsColse) { base.Close(); } } }