HI! I have table inform, but I want export data from database by using below code. It’s worked and I have some problem. I want new id in excel by order. In below code it’s not show new id.
using (SqlConnection con = new SqlConnection(UserData))
{
SqlCommand cmd = con.CreateCommand();
string sql = @"SELECT row_number() over(order by ID) AS NID, LastName, Name, Birthday, Address FROM Inform ORDER BY NID";
cmd.CommandText = sql;
con.Open();
SqlDataAdapter sda = new SqlDataAdapter();
try
{
sda.SelectCommand = cmd;
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
string path = Server.MapPath("exportedfiles\\");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
File.Delete(path + "MutilationSheet.xlsx");
Excel.Application xlAppToExport = new Excel.Application();
xlAppToExport.Workbooks.Add("");
Excel.Worksheet xlWorkSheetToExport = default(Excel.Worksheet);
xlWorkSheetToExport = (Excel.Worksheet)xlAppToExport.Sheets["Лист1"];
int iRowCnt = 4;
xlWorkSheetToExport.Cells[1, 1] = "Inform about mutilation";
Excel.Range range = xlWorkSheetToExport.Cells[1, 1] as Excel.Range;
range.EntireRow.Font.Name = "Palatino Linotype";
range.EntireRow.Font.Bold = true;
range.EntireRow.Font.Size = 20;
xlWorkSheetToExport.Range["A1:E1"].MergeCells = true;
xlWorkSheetToExport.Cells[iRowCnt - 1, 1] = "NID";
xlWorkSheetToExport.Cells[iRowCnt - 1, 2] = "LastName";
xlWorkSheetToExport.Cells[iRowCnt - 1, 3] = "Name";
xlWorkSheetToExport.Cells[iRowCnt - 1, 4] = "Birthday";
xlWorkSheetToExport.Cells[iRowCnt - 1, 5] = "Address";
int i;
for (i = 0; i <= dt.Rows.Count - 1; i++)
{
xlWorkSheetToExport.Cells[iRowCnt, 1] = dt.Rows[i].Field<Int32>("NID");
xlWorkSheetToExport.Cells[iRowCnt, 2] = dt.Rows[i].Field<string>("LastName");
xlWorkSheetToExport.Cells[iRowCnt, 3] = dt.Rows[i].Field<string>("Name");
xlWorkSheetToExport.Cells[iRowCnt, 4] = dt.Rows[i].Field<string>("Birthday");
xlWorkSheetToExport.Cells[iRowCnt, 5] = dt.Rows[i].Field<string>("Address");
iRowCnt = iRowCnt + 1;
}
Excel.Range range1 = xlAppToExport.ActiveCell.Worksheet.Cells[11, 1] as Excel.Range;
range1.AutoFormat();
xlWorkSheetToExport.SaveAs(path + "MutilationSheet.xlsx");
xlAppToExport.Workbooks.Close();
xlAppToExport.Quit();
xlAppToExport = null;
xlWorkSheetToExport = null;
lblConfirm.Text = "Data Exported Successfully";
lblConfirm.Attributes.Add("style", "color:green; font: normal 14px Palatino Linotype;");
btView.Attributes.Add("style", "display:block");
btDownLoadFile.Attributes.Add("style", "display:block");
}
}
catch (Exception ex)
{
lblConfirm.Text = ex.Message.ToString();
lblConfirm.Attributes.Add("style", "color:red; font: bold 14px/16px Palatino Linotype");
}
finally
{
sda.Dispose();
sda = null;
con.Close();
}
}