无法将数据写入到现有的XLSX文件 [英] Can't write data to existing xlsx file

查看:217
本文介绍了无法将数据写入到现有的XLSX文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了下面

            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 .

推荐答案

我找到了答案。我只是改了行的

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"]; 

和它的工作!。

由于工作表Sheet1 是工作表的默认名称和它在我的文件中的行存在:

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

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



实际上,在这种情况下, package.Workbook.Worksheets.Add 表示添加工作表的名字,我发现它没有添加工作表的名称,因为它已经存在。

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.

这篇关于无法将数据写入到现有的XLSX文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆