#region Export the data in DataGridView into Excel /// <summary> /// Export the data in DataGridView into Excel /// </summary> /// <param name="gridView">DataGridView object</param> /// <param name="isShowExcle">whether show the Excel interface</param> /// <returns></returns> public bool ExportDataGridview(DataGridView gridView, bool isShowExcle) { if (gridView.Rows.Count == 0) return false;
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
//Build Excel Object. try { excel.Application.Workbooks.Add(true); excel.Visible = isShowExcle; Worksheet sheet = excel.ActiveSheet as Worksheet;
//Generate Report Title Range range = null; range = sheet.get_Range(excel.Cells[1, 1], excel.Cells[1, gridView.Columns.Count]); range.MergeCells = true; // merge the cells range.RowHeight = 20; // set row heigth range.ColumnWidth = 20; // set coloum width range.Font.Bold = true; // bold the font range.Font.Size = 20; // set font size range.Font.ColorIndex = 5; // set font color range.HorizontalAlignment = XlHAlign.xlHAlignCenter; // set align center range.VerticalAlignment = XlVAlign.xlVAlignCenter;// set cell align vertial center range.Value2 = "Asset Disposition Table";// set the value of cell
//Generate the column name of the gridview. for (int i = 0; i < gridView.ColumnCount; i++) { excel.Cells[2, i + 1] = gridView.Columns[i].HeaderText; }
//Fill the data from the gridview. for (int i = 0; i < gridView.RowCount - 1; i++) { for (int j = 0; j < gridView.ColumnCount; j++) { if (gridView[j, i].ValueType == typeof(string)) { excel.Cells[i + 3, j + 1] = "'" + gridView[j, i].Value.ToString(); } else { excel.Cells[i + 3, j + 1] = gridView[j, i].Value.ToString(); } } } return true; } catch (Exception ex) { return false; MessageBox.Show("Please install the excel application first before you use export function", "Exception"); } finally { excel.Quit(); excel = null; }
} #endregion 轉載自:http://hi.baidu.com/%C4%AB%C1%E9%D2%C1%C8%BB/blog/item/f5bec154dcb4cd51574e002e.html |
把DataGridView的結果傳入Excel
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.