You're getting an exception because you are creating a new FileStream
for writing (FileAccess.Write
) and passing it to the constructor of HSSFWorkbook
which is expecting to be able to read from the stream. The file is corrupt because the FileStream
is creating the file, but nothing is ever written to it.
If you're just trying to create a new blank workbook and save it to a file, you can do that as shown below. Note that you need to add at least one worksheet to the new workbook, or you will still generate a corrupt file.
// Create a new workbook with an empty sheet
HSSFWorkbook wbXLS = new HSSFWorkbook();
ISheet sheet = wbXLS.CreateSheet("Sheet1");
// Write the workbook to a file
string fileName = @"C:\Users\andrei.tudor\Documents\TipMacheta.xls";
using (FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
wbXLS.Write(stream);
}
If you're trying to read an existing workbook OR create a new one if it doesn't exist, you need to do something like this:
string fileName = @"C:\Users\andrei.tudor\Documents\TipMacheta.xls";
HSSFWorkbook wbXLS;
try
{
// Try to open and read existing workbook
using (FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
wbXLS = new HSSFWorkbook(stream);
}
}
catch (FileNotFoundException)
{
// Create a new workbook with an empty sheet
wbXLS = new HSSFWorkbook();
wbXLS.CreateSheet("Sheet1");
}
ISheet sheet = wbXLS.GetSheetAt(0); // Get first sheet
// ...
// Write workbook to file
using (FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
wbXLS.Write(stream);
}