首页 > 解决方案 > 在 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();

问题是我只能生成两个报告,然后我尝试生成第三方并且应用程序卡住了,我没有得到任何异常,它只是卡住了,但只有当我尝试生成第三个文档时

标签: c#excel

解决方案


你没有增加变量“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();

推荐阅读