Can't write data to existing xlsx file

与世无争的帅哥 提交于 2019-12-23 02:44:10

问题


I wrote this code below

            string filePath = @"C:\report_data.xlsx";

            // Saves the file via a FileInfo 
            var file = new FileInfo(filePath);

            // Creates the package and make sure you wrap it in a using statement
            using (var package = new ExcelPackage(file))
            {
                // Adds a new worksheet to the empty workbook
                OfficeOpenXml.ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Report System - " + DateTime.Now.ToShortDateString());

                // Starts to get data from database
                for (int row = 1; row < 10; row++)
                {
                    // Writes data from sql database to excel's columns
                    for (int col = 1; col < 10; col++)
                    {                            
                        worksheet.Cells[row, col].Value = row * col;
                    }// Ends writing data from sql database to excel's columns

                }// Ends getting data from database


                // Saves new workbook and we are done!
                package.Save();
            }

When i opened the file , it had nothing and the page was blank. But when i saw the file size , it increased . Why was the page blank while the file size increased and how can i write data to it ?

Remark : When i tried deleting the existing file and run a program, the program generated the file and the file had values displayed in the columns . On the other hand , i tried creating file first and then run the program and the result was blank like i said above .


回答1:


I found out the answer . I just changed the line at

OfficeOpenXml.ExcelWorksheet worksheet = 
  package.Workbook.Worksheets.Add("Report System - " +
    DateTime.Now.ToShortDateString());

to

OfficeOpenXml.ExcelWorksheet worksheet = 
  package.Workbook.Worksheets["Sheet1"]; 

and it worked !!.

Because Sheet1 is the default name of worksheet and it existed in my file at line:

string filePath = @"C:\report_data.xlsx";

Actually, in this case, package.Workbook.Worksheets.Add means to add the worksheet's name and I found that it didn't have to add the worksheet's name because it already exists.



来源:https://stackoverflow.com/questions/17486391/cant-write-data-to-existing-xlsx-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!