NPOI - saving a workbook created from a template file

This is the second time I do NPOI. I am creating a book from an excel file of a template like this.

string dldir = AppDomain.CurrentDomain.BaseDirectory + "Download\\excel\\"; string uldir = AppDomain.CurrentDomain.BaseDirectory + "Upload\\default_export_file\\"; string filename = DateTime.Now.ToString("yyyy-Md") + "_" + user.first_name + "_" + query.default_export_filename; System.IO.File.Delete(Path.Combine(dldir, filename)); //System.IO.File.Copy(Path.Combine(uldir, query.default_export_filename), Path.Combine(dldir, filename)); HSSFWorkbook hssfwb; using (FileStream file = new FileStream(Path.Combine(uldir, query.default_export_filename), FileMode.Open, FileAccess.ReadWrite)) { hssfwb = new HSSFWorkbook(file); } MemoryStream mstream = new MemoryStream(); hssfwb.Write(mstream); FileStream xfile = new FileStream(Path.Combine(dldir, filename), FileMode.Create, System.IO.FileAccess.Write); byte[] bytes = new byte[mstream.Length]; mstream.Read(bytes, 0, (int)mstream.Length); xfile.Write(bytes, 0, bytes.Length); xfile.Close(); mstream.Close(); 

But when I checked the created file. It does not contain anything. The size is correct. But the content is just gaps. And I could not open it in MS Excel. I repeated and traced the code, but I cannot find what makes it just write spaces.

Does anyone know why this is happening

FYI: I am using VS 2010, ASP.Net MVC 4 and NPOI 1.2.5 installed from the NuGet Gallery

+4
source share
1 answer

How about this:

 MemoryStream mstream = new MemoryStream(); hssfwb.Write(mstream); FileStream xfile = new FileStream(Path.Combine(dldir, filename), FileMode.Create, System.IO.FileAccess.Write); byte[] bytes = new byte[mstream.Length]; mstream.Read(bytes, 0, (int)mstream.Length); xfile.Write(bytes, 0, bytes.Length); xfile.Close(); mstream.Close(); 

Modified:

 FileStream xfile = new FileStream(Path.Combine(dldir, filename), FileMode.Create, System.IO.FileAccess.Write); hssfwb.Write(xfile); xfile.Close(); 
+9
source

Source: https://habr.com/ru/post/1440522/


All Articles