Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I'm want export data from database in to range identified of worksheet existing included old data in excel file. I try to export but i can't.
Please suggest. Thanks![enter image description here][1]

http://www.flickr.com/photos/118251321@N02/12743240805/
Posted
Comments
Maciej Los 24-Feb-14 16:34pm    
What to suggest?

 
Share this answer
 
try
{
if (dt == null || dt.Columns.Count == 0)
{
throw new Exception("ExportToExcel: Null or empty input table!\n");
}

Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel._Worksheet xlWorkSheet;
Microsoft.Office.Interop.Excel.Range xlRange = null;
object misValue = Missing.Value;

xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.Visible = false;

xlWorkBook = xlApp.Workbooks.Open(FileParth, misValue, false, misValue, misValue, misValue, true, misValue, misValue, misValue, misValue, misValue, false, misValue, misValue);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Sheets[SheetName];
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Sheets[1];
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.ActiveSheet;
xlWorkSheet.Activate();

xlRange = xlWorkSheet.get_Range(StartRange, EndRange);
int i = 0;
int j = 0;
//Header
for (i = 0; i < dt.Columns.Count; i++)
{
xlRange.Cells[1, i + 1] = dt.Columns[i].ColumnName;

}
//Datas
for (i = 0; i < dt.Rows.Count; i++)
{
for (j = 0; j < dt.Columns.Count; j++)
{
xlRange.Cells[i + 2, j + 1] = dt.Rows[i][j];
}
}
if (FileParth != null || FileParth != "")
{
try
{
xlApp.ActiveWorkbook.SaveAs(FileParth);
xlApp.Quit();

xlWorkSheet = null;
xlWorkBook = null;
xlApp = null;
}
catch (Exception ex)
{
throw new Exception("Can not save file" + ex.Message);
}
}
else
{
xlApp.Visible = true;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
C#

 
Share this answer
 

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