Reputation: 35
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.
Upvotes: 1
Views: 707
Reputation: 497
Create a DataTable object dedicated for exceptions e.g.:
DataTable dtException = new DataTable();
Add all those DataRows in dtException which gets fail
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); } }
Upvotes: 1