Reputation: 15
I have a template in excel, with which I make reports from my application.
Each time I generate a report, it is saved in a folder with a fixed name and a variable so that it is not always the same document.
I have this code to open the template
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);
With this I save and I generate the name with a counter in 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();
The problem is that I can only generate two reports but then I try to generate a third party and the application gets stuck and I do not get any exception, it only gets stuck, but it's only when I try to generate a third document
Upvotes: 0
Views: 50
Reputation: 13756
You are not increasing variable "i". You should declare it outside while loop and then increase before usage:
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();
Upvotes: 2
Reputation: 1270
Move your counter variable initialisation outside of the loop
string paths= @"path";
string name= "Report_.xlsx";
int i = 1;
while (File.Exists(System.IO.Path.Combine(paths, name)))
{
name= string.Format("Report_{0}.xlsx",i);
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();
Upvotes: 0