Created
December 8, 2013 03:06
-
-
Save kalashnikovisme/7852903 to your computer and use it in GitHub Desktop.
Export DataGridView to Excel. You must have "export.xlt" file in project directory.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void ExportToExcel(DataGridView grid) { | |
ApplicationClass Excel = new ApplicationClass(); | |
XlReferenceStyle RefStyle = Excel.ReferenceStyle; | |
Excel.Visible = true; | |
Workbook wb = null; | |
String TemplatePath = System.Windows.Forms.Application.StartupPath + @"\export.xlt"; | |
try { | |
wb = Excel.Workbooks.Add(TemplatePath); // !!! | |
} catch (System.Exception ex) { | |
throw new Exception("Template is unavailable " + TemplatePath + "\n" + ex.Message); | |
} | |
Worksheet ws = wb.Worksheets.get_Item(1) as Worksheet; | |
for (int j = 0; j < grid.Columns.Count; ++j) { | |
(ws.Cells[1, j + 1] as Range).Value2 = grid.Columns[j].HeaderText; | |
for (int i = 0; i < grid.Rows.Count; ++i) { | |
object Val = grid.Rows[i].Cells[j].Value; | |
if (Val != null) { | |
(ws.Cells[i + 2, j + 1] as Range).Value2 = Val.ToString(); | |
} | |
} | |
} | |
ws.Columns.EntireColumn.AutoFit(); | |
Excel.ReferenceStyle = RefStyle; | |
ReleaseExcel(Excel as Object); | |
} | |
private void ReleaseExcel(object excel) { | |
Marshal.ReleaseComObject(excel); | |
GC.GetTotalMemory(true); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment