简体   繁体   中英

Create Excel file from C# SQL

I have a ASP.NET Web Application where I am importing an Excel file (.xlsx) and storing the data in a database.

Here is my code to read the Excel file:

private void ImportBulkRegistraion(HttpContext context) 
{
 if (context.Request.Files.Count > 0) 
 {
  HttpFileCollection files = context.Request.Files;
  HttpPostedFile MyFile = files[0];

  DataTable dt = new DataTable();
  using(var excel = new ExcelPackage(MyFile.InputStream)) 
  {
   //loop for all of sheets
   for (int sheetcount = 1; sheetcount <= 1; sheetcount++) 
   {
    ExcelWorksheet worksheet = excel.Workbook.Worksheets[sheetcount];
    ExcelCellAddress startCell = worksheet.Dimension.Start;
    ExcelCellAddress endCell = worksheet.Dimension.End;

    // place all the data into DataTable
    for (int row = startCell.Row; row <= endCell.Row; row++) 
    {
     if (row == 1) 
     {
      //Add columns
      if (sheetcount == 1)
       for (int col = startCell.Column; col <= endCell.Column; col++)
        dt.Columns.Add(worksheet.Cells[row, col].Value.ToString());
     } 
     else
     {
      //Add Rows
      DataRow dr = dt.NewRow();
      int x = 0;
      for (int col = startCell.Column; col <= endCell.Column; col++)
       dr[x++] = worksheet.Cells[row, col].Value;
      dt.Rows.Add(dr);
     }
    }
   }
  }
  ExportUserToDB(dt);
 }
}

//ExportUserToDB(dt); function calls the Stored Procedure where I am inserting the rows into the database.

I want to generate an Excel file where if any of the rows from the input Excel file fails to process, the same rows will be stored in this newly created Excel file (in the same format), which can be fixed manually and then reprocessed again.

For example: If a row has Name column with name as "O'Mac", is not processed by SQL. This is a failed row and should be inserted into newly created Excel file.

  1. Create a DataTable object dedicated for exceptions eg:

    DataTable dtException = new DataTable();

  2. Add all those DataRows in dtException which gets fail

  3. Write a method eg WriteException() and pass dtException to write all exceptions in Excel sheet:

private void WriteException(DataTable dt)
        {
using (ExcelPackage excel = new ExcelPackage()) { excel.Workbook.Worksheets.Add("Exceptions");

var worksheet = excel.Workbook.Worksheets["Exceptions"]; worksheet.Cells["A1"].LoadFromDataTable(dt,false); FileInfo excelFile = new FileInfo(@"C:\Temp\AllExceptions.xlsx"); excel.SaveAs(excelFile); } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM