Hi
i want to add new sheet and populate data from data table into excel from windows application c#.
If the excel is already existing i have to create a new sheet for the same excel and get data from db using datatable and save.
while adding new sheet i get typemismatch error
Please help.
Code attached.
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand("select * from tblBrand", con);
con.Open();
try
{
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = cmd;
System.Data.DataTable dt = new System.Data.DataTable();
DataSet ds = new DataSet("New_data");
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
sda.Fill(dt);
ds.Tables.Add(dt);
string folder = Directory.GetParent(Directory.GetCurrentDirectory()).FullName + "\\OutPut\\";
using (XLWorkbook wb = new XLWorkbook())
{
if(System.IO.File.Exists(folder + "sample.xlsx"))
{
Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
app.DisplayAlerts = false;
app.DefaultSaveFormat = XlFileFormat.xlOpenXMLWorkbook;
Excel.Workbook xwb = app.Workbooks.Open(folder + "sample.xlsx", 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
Excel.Sheets sheet = xwb.Worksheets;
var xlNewSheet = (Excel.Worksheet)sheet.Add(sheet[1], Type.Missing, Type.Missing, Type.Missing);
xlNewSheet.Name = "newsheet";
// xlNewSheet.Cells[0, 0] = xwb.Worksheets.Add(ds);
//xlNewSheet = xwb.Worksheets.Add(dt);
xlNewSheet = (Excel.Worksheet)xwb.Worksheets.Add(dt);
xlNewSheet = (Excel.Worksheet)xwb.Worksheets.get_Item(1);
xlNewSheet.Select();
xwb.Save();
xwb.Close();
releaseObject(xlNewSheet);
releaseObject(sheet);
releaseObject(xwb);
releaseObject(app);
}
else
{
wb.Worksheets.Add(dt, "Brands");
wb.SaveAs(folder + "sample.xlsx");
}
}
con.Close();
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
This line i get error.
xlNewSheet = (Excel.Worksheet)xwb.Worksheets.Add(dt);