NPOI corrupting xlsm workbook - c#

I am required to write some data into an macro enabled workbook which was developed in 1998, i am using NPOI dotnet core library for this task. I am able to write the values into the excel correctly, however i am seeing that alignment and formatting of the sheets is lost. Screenshots below:
First one shows the file after open the file using NPOI and downloading the same, and second shows the file when it is locally opened.
below is the code i am using
public XSSFWorkbook OpenExcelFile(string filePath, string tempSavePath)
{
using (var stream = new FileStream(tempSavePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
var temphssfwb = new XSSFWorkbook(OPCPackage.Open(filePath));
temphssfwb.Write(stream);
}
XSSFWorkbook hssfwb;
hssfwb = new XSSFWorkbook(OPCPackage.Open(tempSavePath));
hssfwb.CreateSheet("casevalidationsheet");
return hssfwb;
}
Can someone please help me understand why NPOI is ruining the alignment of my excel workbook?

Related

How to save a .xltm file to .xlsm with OpenXML?

Ive been using the OpenXmlPackage.SaveAs to save my template files in to excel (.xltx to .xlsx) But when it comes to a macro enabled .xltm the file gets corrupt when saving to .xlsm
I have been reading in the help sections for this API and various threads online but i couldnt find anything covering this so i could get it working.
//open the excel using openxml sdk
using (SpreadsheetDocument doc = SpreadsheetDocument.CreateFromTemplate(fileOpen))
{
doc.SaveAs(fileClose);
}
"Excel cannot open the file 'filename.xlsx' because the file format for the file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."
Anyone out there that have a idea regarding this? Thanks in advance.
This would do the trick.
byte[] byteArray = File.ReadAllBytes(sDocpath + inputPath);
using (MemoryStream stream = new MemoryStream())
{
stream.Write(byteArray, 0, (int)byteArray.Length);
using (SpreadsheetDocument spreadsheetDoc = SpreadsheetDocument.Open(stream, true))
{
// Change from template type to workbook type
spreadsheetDoc.ChangeDocumentType(DocumentFormat.OpenXml.SpreadsheetDocumentType.MacroEnabledWorkbook);
}
File.WriteAllBytes(dirPath + outputPath, stream.ToArray());
}

Npoi xls file save corrupts excel file

So I am able to open and dig through an xls (Excel 97-2003) file. However, the problem is when I try to save it. After I save it, and it succeeds, I then go and manually open the Excel file and get an error saying that it cannot open the Excel file and that it is corrupt. This happens regardless of whether I make any changes or not.
I am still able to, within the program, open the excel file and read through the data.
I am using NPOI 2.2.1 and 2.3.0 (which I installed via Nuget). Both versions have the same results.
string excelLocation = settings.GetExcelDirectory() + week.ExcelLocation;
HSSFWorkbook wbXLS;
// Try to open and read existing workbook
using (FileStream stream = new FileStream(excelLocation, FileMode.Open, FileAccess.Read))
{
wbXLS = new HSSFWorkbook(stream);
}
ISheet sheet = wbXLS.GetSheet("Schedule");
using (FileStream stream = new FileStream(excelLocation, FileMode.Create, FileAccess.Write))
{
wbXLS.Write(stream);
}
Do you have multi-line cell contents (with a line break)?
I just came across such a problem with my column headers in row 0.
Excel encodes a line break by replacing it with _x000a_ (i.e. line1_x000a_line2), NPOI doesn't do that.
Tried with nuget 2.3.0 and xlsx file, but might also be helpful in your case.
I worked around (and verified the cause) by replacing line feeds before saving:
// Encode LineFeeds in column headers (row 0)
IRow rowColHeaders = sheet.GetRow(0);
foreach (ICell cell in rowColHeaders.Cells)
{
string content = cell.StringCellValue;
if (content.Contains("\n"))
cell.SetCellValue(content.Replace("\n", "_x000a_"));
}
try something like
FileStream sw = File.Create(excelLocation);
wbXLS.Write(sw);
sw.Close();

Programatically Create Excel Sheets from different templates using a Addin

I am developing an Excel Addin that is able to fetch data from our database.Instead of dumping the data directly , I would like to have the data presented in a nice format. I have got our local VBA expert to develop a templates for the same since there can be multiple sheets all of which can have different formats.
It is while adding the worksheet that I am stuck at.
string TemplateFileLocation = Path.GetFullPath(fileName);
if(File.Exists(fileName))
{
Worksheet newWorkSheet = (WorkSheet)Globals.ThisAddin.Aplication.Worksheets.Add(Missing.Value,Missing.Value,1,TemplateFileLocation);
}
The code crashes while it hits this location.
The Error code returned is : 0x800A03EC
I have verified that the path to the template file is correct.
Each of these templates have only one work sheet.
You can use EPPlus
using System.IO;
using System.Reflection;
using OfficeOpenXml;
//Create a stream of .xlsx file contained within my project using reflection
Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("EPPlusTest.templates.VendorTemplate.xlsx");
//EPPlusTest = Namespace/Project
//templates = folder
//VendorTemplate.xlsx = file
//ExcelPackage has a constructor that only requires a stream.
ExcelPackage pck = new OfficeOpenXml.ExcelPackage(stream);

Can't edit the existing Excel file with NPOI?

I've tried creating a new Excel file with NPOI and it works OK, reading (only) an Excel file is also OK. However now I want to open an existing Excel file and append some rows on it, it's crashed right at the code line of the NPOI.HSSF.UserModel.HSSFWorkbook constructor. Here is the code:
using(FileStream fs = new FileStream(myFile, FileMode.Append)){
HSSFWorkbook wb = new HSSFWorkbook(fs); //<-- It is crashed right at here
....
}
There is no exception detail, it just shows a window saying that the app is crashed and give 3 options to choose, the middle one is to close the application:
snapshot
That's why I can't understand and feel hard to solve it.
If I change the FileMode to FileMode.Open, the constructor can work well, but that's just for reading. I think there is some thing related to FileAccess policy and tried this:
using(FileStream fs = new FileStream(myFile, FileMode.Append, FileAccess.ReadWrite)){//<-- However it is crashed right at here
HSSFWorkbook wb = new HSSFWorkbook(fs);
....
}
I've tried a workaround by opening (read only) the existing Excel file, copy 1 sheet of it and add this sheet to a new HSSFWorkbook and write (write only) to a new file stream, however there is no way to do that, because the HSSFWorkbook has no collection of Worksheet and there is also no Add method, the new sheet is just created by CreateSheet() method. It's so annoying.
Could you please help me with this? I'm trying NPOI first, then I'll try EPPlus.Your help would be highly appreciated.Thanks.
What's your file format? xls or xlsx? If xlsx, you can try NPOI 2.0 now. xlsx is supported.
Here is the download link: https://npoi.codeplex.com/releases/view/112932

.NET C# - Importing Excel File - Sheet Name!

I'm using the NPOI Library to import some data from an excel sheet to my database.
One early issue I'm curious about, is typically, to begin, you would have something like this:
snippet
using (FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read))
{
HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs);
HSSFSheet sheet = templateWorkbook.GetSheet("Sales");
My query is, what happens when the name of the worksheet is different each time, e.g. I plan to import sales data, and the sheets within the workbooks I receive from suppliers are titled by date.
Is there any way that you can specify GetSheet(); to just get the first sheet in the workbook?
Any pointers would be much appreciated,
thanks guys :)
Without trying it out I'd assume that you're looking for getSheetAt.
So it would be:
HSSFSheet sheet = templateWorkbook.GetSheetAt(0);

Categories

Resources