I cannot open the xlsm file after re-writing over it

66 Views Asked by At

I have an xlsm template with some macros in it that I need. below is my code to copy the file from one folder to another and than change the data in said file.

I am using the NPOI library to do this.

string sourceFilePath = oldtemplatePath;
            string targetFolderPath = folderPath;

            // Get the file name from the source file path
            string fileName = Path.GetFileName(sourceFilePath);

            // Combine the target folder path and the file name to get the full target path
            string targetFilePath = Path.Combine(targetFolderPath, fileName);
            try
            {
                // Use File.Copy to copy the file
                File.Copy(sourceFilePath, targetFilePath, true); // Set the third parameter to true to overwrite the file if it already exists

                Console.WriteLine("File copied successfully!");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }

            using (FileStream fs = File.Open(targetFilePath, FileMode.Open, FileAccess.ReadWrite))
            {
                IWorkbook workbook = new XSSFWorkbook(OPCPackage.Open(fs));
                ExcelHeaderSheet(workbook, smCode, fullFilePathName, headerFileDesc);
                ExcelDetailsSheet(workbook, dt);
                ExcelTrailerSheet(workbook, numberOfProductCodes);
                using (FileStream outputStream = new FileStream(targetFilePath, FileMode.Open))
                {
                    workbook.Write(outputStream);
                }
            }

The code runs fine but when I go and try to open the new file it tells me that the file format or the extension is not valid, did I do something wrong or am I missing something?

0

There are 0 best solutions below