Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
C#
public void ExportToExcel(DataTable DT, string reportName)
   {
FileInfo newFile = new FileInfo(@"C:\\Reports\\" + reportName + ".xlsx");
              

                  if (newFile.Exists)
                  {
                      newFile.Delete();  // ensures we create a new workbook
                     
                  }
                  newFile = new FileInfo(@"C:\\techsoft\\Reports\\" + reportName + ".xlsx");

                  using (ExcelPackage pck = new ExcelPackage(newFile))
                  {
                      try
                      {
                          ExcelWorksheet ws = pck.Workbook.Worksheets.Add(reportName);
                          ws.Cells["A1"].LoadFromDataTable(DT, true);
                          pck.Save();
                          
                      }
                      finally
                      {
                          ((IDisposable)pck).Dispose();                                                    
                      }
                  }
            }
Posted
Updated 28-Apr-15 2:34am
v2

Make sure the file is not open by you or by someone else.
 
Share this answer
 
Things that can cause this:

1. Someone else has the spreadsheet open (either in Excel or via another program) - unlikely in this case (but not impossible) as it is located on your C: drive

2. You have the spreadsheet open in Excel

3. This is not the first time you have run this program and it does not release the resources correctly - try closing the program / Visual Studio (and tidy up the code).

4. Some earlier processing in this program still has the file open (Follow instructions for 3 above).

5. Check using Task Manager to see if a previous instance of Excel is still in memory - it may be locking the file.
 
Share this answer
 
Comments
Karthik_Mahalingam 28-Apr-15 13:54pm    
5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900