0

I'm writing a program to process some excel documents, the program is written in C# in Visual Studio 2010, and I'm using the NPOI library.

I notice the I was not able to use CloneSheet() for the xlsm file, but I was able to do so with xlsx.

CloneSheet() is a function that I really need for the process, so I really would like to get it working instead of copy everything cell by cell.

I thought of converting the file to xlsx. I was able to do it manually, but not programmatically.

This is the code I wrote to attempt to do so:

XSSFWorkbook workbook;

//read original xlsm file into workbook
using (FileStream file = new FileStream(@"OriginalFile\" + filename, FileMode.Open, FileAccess.Read))
{ workbook = new XSSFWorkbook(file); }

//change file extension to xlsx and save in a new location
filename = Path.ChangeExtension(filename, "xlsx");
if (!Directory.Exists("NewFile"))
    Directory.CreateDirectory("NewFile");
FileStream stream = new FileStream(("NewFile\\New" + filename), FileMode.Create, System.IO.FileAccess.Write);
workbook.Write(stream);
stream.Close();

//read the newly created file from the new location
using (FileStream file = new FileStream(@"NewFile\\New" + filename, FileMode.Open, FileAccess.Read))
{ workbook = new XSSFWorkbook(file); }

The above code will create the new xlsx file, but the file cannot be open and seems to be corrupted...

I've been googling for a while and couldn't seem to find a solution, can anyone help or point me to the right direction?

--EDIT---

I tried a different method using Open XML I found here, but I have the same issue, where the file is created but I can't open the file.

However, the file doesn't seem to be corrupted. My program that is reading the file have no problem reading the data, and when I try to open the file in excel it's saying "The file is a macro-free file, but contains macro-enable content."

Seems like I'm getting closer, but I need to be able to open the output file otherwise it's no use....

Community
  • 1
  • 1
sora0419
  • 2,308
  • 9
  • 39
  • 58
  • have you seen [**this**](http://msdn.microsoft.com/en-us/library/ms178800.aspx)? –  Mar 11 '14 at 14:32
  • @mehow the method does not work for me, my guess is that its only supported in VS2013? I tried the sample from the page and my code won't even compile. Also, the issue with xlsm is that I can't even open the output file. – sora0419 Mar 11 '14 at 14:45
  • hmm totally strange.. –  Mar 11 '14 at 14:53

1 Answers1

0

You may have to roll your own method: iterate rows then cells. This post Copy Row Helper got me started. You'll have to modify it to use two workbooks. This method will copy data and formulas. CellStyles will have to be recreated as they they specific to the originating workbook.

David Robbins
  • 9,996
  • 7
  • 51
  • 82