J'ai un datagridview dans c # où je montre des loggings. Maintenant, selon mon exigence, je dois exporter ceci dans excel.So j'ai écrit la méthode suivante pour cette …
public static void ExportToExcel(DataGridView dgView) { Microsoft.Office.Interop.Excel.Application excelApp = null; try { // instantiating the excel application class object misValue = System.Reflection.Missing.Value; excelApp = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook currentWorkbook = excelApp.Workbooks.Add(Type.Missing); Microsoft.Office.Interop.Excel.Worksheet currentWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)currentWorkbook.ActiveSheet; currentWorksheet.Columns.ColumnWidth = 18; if (dgView.Rows.Count > 0) { currentWorksheet.Cells[1, 1] = DateTime.Now.ToSsortingng("s"); int i = 1; foreach (DataGridViewColumn dgviewColumn in dgView.Columns) { // Excel work sheet indexing starts with 1 currentWorksheet.Cells[2, i] = dgviewColumn.Name; ++i; } Microsoft.Office.Interop.Excel.Range headerColumnRange = currentWorksheet.get_Range("A2", "G2"); headerColumnRange.Font.Bold = true; headerColumnRange.Font.Color = 0xFF0000; //headerColumnRange.EntireColumn.AutoFit(); int rowIndex = 0; for (rowIndex = 0; rowIndex < dgView.Rows.Count; rowIndex++) { DataGridViewRow dgRow = dgView.Rows[rowIndex]; for (int cellIndex = 0; cellIndex < dgRow.Cells.Count; cellIndex++) { currentWorksheet.Cells[rowIndex + 3, cellIndex + 1] = dgRow.Cells[cellIndex].Value; } } Microsoft.Office.Interop.Excel.Range fullTextRange = currentWorksheet.get_Range("A1", "G" + (rowIndex + 1).ToSsortingng()); fullTextRange.WrapText = true; fullTextRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft; } else { ssortingng timeStamp = DateTime.Now.ToSsortingng("s"); timeStamp = timeStamp.Replace(':', '-'); timeStamp = timeStamp.Replace("T", "__"); currentWorksheet.Cells[1, 1] = timeStamp; currentWorksheet.Cells[1, 2] = "No error occured"; } using (SaveFileDialog exportSaveFileDialog = new SaveFileDialog()) { exportSaveFileDialog.Title = "Select Excel File"; exportSaveFileDialog.Filter = "Microsoft Office Excel Workbook(*.xlsx)|*.xlsx"; if (DialogResult.OK == exportSaveFileDialog.ShowDialog()) { ssortingng fullFileName = exportSaveFileDialog.FileName; currentWorkbook.SaveAs(fullFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, System.Reflection.Missing.Value, misValue, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true, misValue, misValue, misValue); currentWorkbook.Saved = true; MessageBox.Show("Exported successfully", "Exported to Excel", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (excelApp != null) { excelApp.Quit(); } } }
Maintenant, une chose étrange se passe lorsque j'essaie d'get le rapport Excel en utilisant ma request, je ne peux pas l'get alors que si j'essaie de l'get en déboguant mon code, j'en prendrais, mais ça prend beaucoup de time. Lors du debugging du code Cette ligne …
Microsoft.Office.Interop.Excel.Range fullTextRange = currentWorksheet.get_Range("A1", "G" + (rowIndex + 1).ToSsortingng());
prend beaucoup de time …
Aidez-moi, s'il vous plaît ..
Excel Interop
ne sera jamais rapide car vous contrôlez à distance une instance de l'application Excel. Vous voudrez peut-être créer un file CSV puis utiliser Excel Interop
pour convertir ceci en un file .xls
ou .xlsx
.
Voici un exemple sur la façon de convertir csv en xls
using Excel = Microsoft.Office.Interop.Excel; Excel.Application excel = new Excel.Application(); Excel.Workbook workBook = excel.Workbooks.Add(); var inputFile = new FileInfo("Book1.csv"); var sheet = Spreadsheet.Read(inputFile); workBook.ActiveSheet = sheet; // unsure about this part, but basically you need to transfer data. workBook.SaveAs(@"C:\Temp\fromCsv.xls"); workBook.Close();
Je pense que la section ci-dessous ralentit beaucoup votre code
int rowIndex = 0; for (rowIndex = 0; rowIndex < dgView.Rows.Count; rowIndex++) { DataGridViewRow dgRow = dgView.Rows[rowIndex]; for (int cellIndex = 0; cellIndex < dgRow.Cells.Count; cellIndex++) { currentWorksheet.Cells[rowIndex + 3, cellIndex + 1] = dgRow.Cells[cellIndex].Value; } }
Je pense qu'il serait beaucoup plus rapide d'exporter DataGridView
vers une feuille de calcul Excel en ne bouclant pas en appelant des Cells
chaque fois, car chaque appel à Cells
est très coûteux lors de l'utilisation de COM.
Je vous suggère de convertir votre DataGridViewColumn
en un tableau 2D, puis d'exporter l'set de DataGridView
d'une seule manière comme ceci:
object[,] toExport = new object[dgView.Rows.Count, dgView.Columns.Count]; for (int row = 0; row < dgView.Rows.Count; row++) { DataGridViewRow dgRow = dgView.Rows[row]; for (int column= 0; column < dgRow.Cells.Count; column++) { toExport[row, column] = dgRow.Cells[row].Value; } } // export in one go instead of looping and accessing Cells each time // use Excel.Application.Transpose(array) if needed ws.get_Range("A3").set_Value(Type.Missing, toExport);
De plus, vous pouvez append un xlApp.ScreenUpdating = false;
au début, puis revenez à true
lorsque vous avez fini de modifier la feuille.