从DataGridView中导出数据至Excel
ImportDataFromDGVToExcel.rar
(42.75 KB)
public bool ExportDataGridView(DataGridView dgv,bool isShowExcel) { SaveFileDialog dlg = new SaveFileDialog();//定义SaveFileDialog各属性 dlg.Filter = "Execl files (*.xls)|*.xls"; dlg.CheckFileExists = false; dlg.CheckPathExists = false; dlg.FilterIndex = 0; dlg.RestoreDirectory = true; dlg.CreatePrompt = true; dlg.Title = "保存为Excel文件"; if (dgv.Rows.Count == 0) return false; else { if (dlg.ShowDialog() == DialogResult.OK) { Stream myStream; //利用文件流来打开Excel文件 myStream = dlg.OpenFile(); StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0)); Excel.Application xlApp=new Excel.Application(); object missing=System.Reflection.Missing.Value; Excel.Workbooks workbooks=xlApp.Workbooks; Excel.Workbook workbook=workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet); Excel.Worksheet worksheet=(Excel.Worksheet)workbook.Worksheets[1];//取得sheet1 xlApp.Visible = isShowExcel; for (int i = 0; i < dgv.ColumnCount; i++) { xlApp.Cells[1, i + 1] = dgv.Columns[i].HeaderText; } for (int i = 0; i < dgv.RowCount - 1; i++) { for (int j = 0; j < dgv.ColumnCount; j++) { if (dgv[j, i].ValueType == typeof(string)) { xlApp.Cells[i + 2, j + 1] = "'" + dgv[j, i].Value.ToString(); } else { xlApp.Cells[i + 2, j + 1] = dgv[j, i].Value.ToString(); } } } return true; } else { return false; } } }