Hello well I have this problem,The code only it can create a new excle file but I want to export my datagrid in a existing excel file. Any help is appreciated.
try
{
if (DataGridView1.DataSource != null)
{
SaveFileDialog fichero = new SaveFileDialog();
fichero.Filter = "Excel (*.xls)|*.xls";
if (fichero.ShowDialog() == DialogResult.OK)
{
Microsoft.Office.Interop.Excel.Application aplicacion;
Microsoft.Office.Interop.Excel.Workbook libros_trabajo;
Microsoft.Office.Interop.Excel.Worksheet hoja_trabajo;
aplicacion = new Microsoft.Office.Interop.Excel.Application();
libros_trabajo = aplicacion.Workbooks.Add();
hoja_trabajo = (Microsoft.Office.Interop.Excel.Worksheet)libros_trabajo.Worksheets.get_Item(1);
//exportar cabeceras DataGridView1
for (int i = 1; i <= this.DataGridView1.Columns.Count; i++)
{
hoja_trabajo.Cells[1, i] = this.DataGridView1.Columns[i - 1].HeaderText;
}
//Recorremos el DataGridView rellenando la hoja de trabajo con los datos
for (int i = 0; i < this.DataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < this.DataGridView1.Columns.Count; j++)
{
hoja_trabajo.Cells[i + 2, j + 1] = this.DataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
libros_trabajo.SaveAs(fichero.FileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal);
libros_trabajo.Close(true);
aplicacion.Quit();
}
}
}
Pertinent to your task, use the underlying DataTable
DataTable dt = DataGridView1.DataSource as DataTable;
and export data from that DataTable dt
to Excel using the following procedure, which utilizes Microsoft.Office.Interop.Excel
object library:
/// <summary>
/// export DataTable to Excel (C#)
/// </summary>
internal static void Export2Excel(DataTable dataTable)
{
object misValue = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application _appExcel = null;
Microsoft.Office.Interop.Excel.Workbook _excelWorkbook = null;
Microsoft.Office.Interop.Excel.Worksheet _excelWorksheet = null;
try
{
// excel app object
_appExcel = new Microsoft.Office.Interop.Excel.Application();
// excel workbook object added to app
_excelWorkbook = _appExcel.Workbooks.Add(misValue);
_excelWorksheet = _appExcel.ActiveWorkbook.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;
// column names row (range obj)
Microsoft.Office.Interop.Excel.Range _columnsNameRange;
_columnsNameRange = _excelWorksheet.get_Range("A1", misValue).get_Resize(1, dataTable.Columns.Count);
// column names array to be assigned to _columnNameRange
string[] _arrColumnNames = new string[dataTable.Columns.Count];
for (int i = 0; i < dataTable.Columns.Count; i++)
{
// array of column names
_arrColumnNames[i] = dataTable.Columns[i].ColumnName;
}
// assign array to column headers range, make 'em bold
_columnsNameRange.set_Value(misValue, _arrColumnNames);
_columnsNameRange.Font.Bold = true;
// populate data content row by row
for (int Idx = 0; Idx < dataTable.Rows.Count; Idx++)
{
_excelWorksheet.Range["A2"].Offset[Idx].Resize[1, dataTable.Columns.Count].Value =
dataTable.Rows[Idx].ItemArray;
}
// Autofit all Columns in the range
_columnsNameRange.Columns.EntireColumn.AutoFit();
}
catch { throw; }
}
just pass dt
as an argument. Optionally, upon data export completion you can save the Workbook
and Quit
Excel app. Furthermore, as mentioned in the comments thread, you can open the existing Excel file (eg "MyExcelFile") and export data to that file, or just re-write the existing file by saving the newly created Workbook
(ie _excelWorkbook
) under the old file name.
The core idea of proposed solution is to run data export procedure on the underlying DataTable
rather than DataGridView
and export entire data Row
at once (instead of cell-by-cell) for better performance.
Hope this may help.
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.