我目前正在使用
EPPlus项目来操作一些.xlsx文件.基本思想是我必须从给定的模板创建一个新文件.
但是当我从模板创建新文件时,表中的所有计算列都搞砸了.
我使用的代码如下:
static void Main(string[] args) { const string templatePath = "template_worksheet.xlsx"; // the path of the template const string resultPath = "result.xlsx"; // the path of our result using (var pck = new ExcelPackage(new FileInfo(resultPath),new FileInfo(templatePath))) // creating a package with the given template,and our result as the new stream { // note that I am not doing any work ... pck.Save(); // savin our work } }
例如,对于.xlsx文件(具有3列的表,最后一个只是其他列的总和),程序会创建一个.xlsx文件,其中最后一列具有相同的值(仅对第一列有效)所有行中的行).
以下图像显示了结果:
现在的问题是:
这里发生了什么 ?我的代码错了吗?
如果没有出现意外行为,我该如何完成这项任务?
解决方法
那绝对是在那里.我自己能够重现它.它与您创建的表有关.如果您打开文件并使用“表格工具”选项卡中的“转换为范围”选项将其删除,则问题就会消失.
我查看了源代码,它在zip级别提取了xml文件,并没有看到任何迹象表明它实际上正在弄乱它们 – 似乎是一个直接的副本.
很奇怪,因为如果我们创建并保存包含来自EPPlus的表的xlsx文件,问题就不存在了.这很好用:
[TestMethod] public void Template_copy_test() { //https://stackoverflow.com/questions/28722945/epplus-with-a-template-is-not-working-as-expected const string templatePath = "c:\\temp\\testtemplate.xlsx"; // the path of the template const string resultPath = "c:\\temp\\result.xlsx"; // the path of our result //Throw in some data var dtdata = new DataTable("tblData"); dtdata.Columns.Add(new DataColumn("Col1",typeof(string))); dtdata.Columns.Add(new DataColumn("Col2",typeof(int))); dtdata.Columns.Add(new DataColumn("Col3",typeof(int))); for (var i = 0; i < 20; i++) { var row = dtdata.NewRow(); row["Col1"] = "String Data " + i; row["Col2"] = i * 10; row["Col3"] = i * 100; dtdata.Rows.Add(row); } var templateFile = new FileInfo(templatePath); if (templateFile.Exists) templateFile.Delete(); using (var pck = new ExcelPackage(templateFile)) { var ws = pck.Workbook.Worksheets.Add("Data"); ws.Cells["A1"].LoadFromDataTable(dtdata,true); for (var i = 2; i <= dtdata.Rows.Count + 1; i++) ws.Cells[i,4].Formula = String.Format("{0}*{1}",ExcelCellBase.GetAddress(i,2),3)); ws.Tables.Add(ws.Cells[1,1,dtdata.Rows.Count + 1,4],"TestTable"); pck.Save(); } using (var pck = new ExcelPackage(new FileInfo(resultPath),templateFile)) // creating a package with the given template,and our result as the new stream { // note that I am not doing any work ... pck.Save(); // savin our work } }
但…..
如果我们打开testtemplate.xlsx,删除表,保存/关闭文件,重新打开,并重新插入运行此问题时显示的完全相同的表:
[TestMethod] public void Template_copy_Test2() { //https://stackoverflow.com/questions/28722945/epplus-with-a-template-is-not-working-as-expected const string templatePath = "c:\\temp\\testtemplate.xlsx"; // the path of the template const string resultPath = "c:\\temp\\result.xlsx"; // the path of our result var templateFile = new FileInfo(templatePath); using (var pck = new ExcelPackage(new FileInfo(resultPath),and our result as the new stream { // note that I am not doing any work ... pck.Save(); // savin our work } }
它必须是拉链复制方法中的东西,但我什么都没有跳出来.
但至少你可以看到解决它的问题.
厄尼
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。