3

Thanks for the help from people on this site, I was able to modify .xlsx file using NPOI. Code is below, but my final goal is to be able to modify .xlsm file cell value. Is there a way to do this? I tried to run with the following code but after won't be able to open the file once i ran the program.

XSSFWorkbook templateWorkbook;
using (FileStream fs = new FileStream(@"C:\Users\jzhu\Desktop\FlexTimeSheetTest.xlsm", FileMode.Open, FileAccess.ReadWrite))
{
    templateWorkbook = new XSSFWorkbook(fs);
    fs.Close();
}

XSSFSheet sheet = (XSSFSheet)templateWorkbook.GetSheet("Sheet1");
sheet.GetRow(0).GetCell(0).SetCellValue("Drago");
sheet.ForceFormulaRecalculation = true;

File.Delete(@"C:\Users\jzhu\Desktop\FlexTimeSheetTest.xlsm");

using (FileStream file = new FileStream(@"C:\Users\jzhu\Desktop\FlexTimeSheetTest.xlsm", FileMode.CreateNew, FileAccess.Write))
{
    templateWorkbook.Write(file);
    file.Close();
}
Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
OPK
  • 4,120
  • 6
  • 36
  • 66

2 Answers2

1

Update your NPOI library to latest version (2.1.3.1 at present time).

Using this version, your code and sample xlsm file with one macro recorded - I got valid file after modifying it by your code.

Excel is able to open it, and macro can be run.

Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
  • I have an issue with .xlsm file download using NPOI and posted a question, please can you help me out on the issue. Question link: http://stackoverflow.com/questions/40078631/issue-downloading-xlsm-document-with-activex-controls-using-npoi?noredirect=1 – RandomUser Oct 17 '16 at 04:56
0
            XSSFWorkbook xlWorkbook;

            using (FileStream file = new FileStream(toEditFile,FileMode.Open, FileAccess.Read))
            {
                xlWorkbook = new XSSFWorkbook(file);
            }

            var xlWorksheet = xlWorkbook.GetSheet(@"sheet");
            // do stuff
            
            using (FileStream file = new FileStream(toEditFile, FileMode.Create, FileAccess.Write))
            {
                xlWorkbook.Write(file);
                file.Close();
            }
Falaq
  • 23
  • 4