- Add a reference to the ‘Microsoft Office 11.0 Object Library’ to your project from COM components.
- Create an object of the ApplicationClass in the Excel namespace
Excel.ApplicationClass ExcelApp = new Excel.ApplicationClass();
- Add a new workbook to the object of the Application class. The parameter to the Add method below is the name of the workbook. We are going to provide the name later (while saving the file). So Type.Missing can be used here.
ExcelApp.Application.Workbooks.Add(Type.Missing);
- Change properties of the Workbook
ExcelApp.Columns.ColumnWidth = 30;
- Copy the contents of the DataGridView object to the cells of the Excel Application object. In the code below ReportDataGrodView is the name of my DataGridView object.
for (int i = 0; i < ReportDataGridView.Rows.Count; i++) { DataGridViewRow row = ReportDataGridView.Rows[i]; for(int j=0; j< row.Cells.Count; j++) { ExcelApp.Cells[i+1, j+1] = row.Cells[j].ToString(); } }
- Save the workbook at any suitable location. In the code below FileName is a string representing full path to the name of the file. This can be obtained from a SaveFileDialog if you want.
ExcelApp.ActiveWorkbook.SaveCopyAs(FileName); ExcelApp.ActiveWorkbook.Saved = true;
- Exit the Excel Application and free up the resources
ExcelApp.Quit();
Roman Pelepei gives smart answers on questions about C# .Net, ASP .Net, WPF and Silverlight programming with examples and source code.
четверг, 21 июля 2011 г.
Exporting a DataGridView to Excel
Подписаться на:
Комментарии к сообщению (Atom)
Комментариев нет:
Отправить комментарий