Quantcast
Channel: NPOI
Viewing all articles
Browse latest Browse all 1621

Commented Issue: XSSFWorkbook Write corrupts XLSX File [12847]

$
0
0
This may be a duplicate of [12616](https://npoi.codeplex.com/workitem/12616), but after much research, I haven't been able to track down a solution.

I compiled NPOI from source in Visual Studio 2013 with a direct pull from GitHub - the NPOI version is 2.0.8. The issue occurs with the NPOI NuGet package as well. I am opening the file with Excel 2010. Consider the following:

```
IWorkbook wb = null;
string file = "numbers.xlsx";

using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read)) {
if (Path.GetExtension(file).Contains("xlsx")) {
wb = new XSSFWorkbook(fs);
} else {
wb = new HSSFWorkbook(fs);
}
}

using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.ReadWrite)) {
wb.Write(fs);
}
```

This will render the output XLSX file unusable. [Case in point on Excel's reaction](http://imgur.com/AMglz1Y,bcCXi0d).

Workbooks created/written in-code with the XSSF API open correctly. XLS files opened/written with the HSSF API are fine with respect to Excel.

The FileMode/FileAccess/FileShare options for the FileStream do not seem to make a difference.

In practice I have been opening far more complex XLSX files, writing a few new cells to the rows therein, and writing back, where after the spreadsheet cannot be opened or subsequently recovered.

I've attached the aforementioned XLSX spreadsheet for testing purposes. Thanks for having a look.
Comments: ** Comment from web user: lukeautry **

I'm running into the same problem. Here's a quick console app to repro the problem (create a new Console app, pull in NPOI package through NuGet, and replace program.cs with the code below).

Attached is the spreadsheet produced by this code.

```
using System.IO;
using NPOI.XSSF.UserModel;

namespace XSSFWorkbookTest
{
class Program
{
static void Main()
{
//Make sure this path exists before you run the console application
const string path = "C:\\Tests\\TestFile1.xlsx";

var xlsxWorkbook = new XSSFWorkbook();

//Using the same example block provided in the sample pack
GenerateData(xlsxWorkbook);

var stream = new MemoryStream();
xlsxWorkbook.Write(stream);

var fileStream = new FileStream(path, FileMode.Truncate, FileAccess.Write);
byte[] bytes = stream.GetBuffer();

fileStream.Write(bytes, 0, bytes.Length);
fileStream.Close();
stream.Close();
}

private static void GenerateData(XSSFWorkbook xlsxWorkbook)
{
var sheet = xlsxWorkbook.CreateSheet("Sheet1");

sheet.CreateRow(0).CreateCell(0).SetCellValue("This is a Sample");
int x = 1;
for (int i = 1; i <= 15; i++)
{
var row = sheet.CreateRow(i);
for (int j = 0; j < 15; j++)
{
row.CreateCell(j).SetCellValue(x++);
}
}
}
}
}
```


Viewing all articles
Browse latest Browse all 1621

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>