c# - 在 C# 中为 Excel 生成名称
问题描述
我在 excel 中有一个模板,我用它从我的应用程序中生成报告。
每次我生成报告时,它都会保存在具有固定名称和变量的文件夹中,因此它并不总是同一个文档。
我有这个代码来打开模板
Excel.Application app = new Excel.Application();
Excel._Workbook book;
Excel._Worksheet sheet;
libro = app.Workbooks.Open(@"path", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
有了这个我保存并生成名称,计数器为 0
string paths= @"path";
string name= "Report_.xlsx";
while (File.Exists(System.IO.Path.Combine(paths, name)))
{
int i = 1;
name= string.Format("Report_{0}.xlsx",i);
}
string fullpath = Path.Combine(paths, name);
book.SaveAs(fullpath, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value, Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange, Excel.XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
book.Close(0);
app.Quit();
问题是我只能生成两个报告,然后我尝试生成第三方并且应用程序卡住了,我没有得到任何异常,它只是卡住了,但只有当我尝试生成第三个文档时
解决方案
你没有增加变量“i”。您应该在 while 循环之外声明它,然后在使用前增加:
string paths= @"path";
string name= "Report_.xlsx";
int i = 0;
while (File.Exists(System.IO.Path.Combine(paths, name)))
{
i++;
name= string.Format("Report_{0}.xlsx",i);
}
string fullpath = Path.Combine(paths, name);
book.SaveAs(fullpath, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value, Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange, Excel.XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
book.Close(0);
app.Quit();
推荐阅读
- java - java中基于泛型类型的决策
- php - WordPress 压缩在 localhost、XAMPP 上不起作用
- javascript - Bootstrap modal 将焦点放在靠近正文输入的弹出窗口上
- java - Java DB新记录插入错误的行
- python-3.x - PyQT5中的按钮使用python
- reactjs - 反应组件重新渲染,即使有键。输入失去焦点
- javascript - Material-UI - 如何在 AppBar 上渲染一些东西?
- php - 使用 JSON 进行计算的 PHP 脚本
- php - 从输入类型 date 传递的日期似乎为空并输出 ..1970-01-01
- vue.js - VueJS scrollBehavior() 参数导致错误