第一种办法:直接在button的Click事件中写代码进行导出:
private void button6_Click(object sender, EventArgs e) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Excel files (*.xls)|*.xls"; saveFileDialog.FilterIndex = 0; saveFileDialog.RestoreDirectory = true; saveFileDialog.CreatePrompt = true; saveFileDialog.Title = "导出Excel文件到"; saveFileDialog.ShowDialog(); try { Stream myStream; myStream = saveFileDialog.OpenFile(); StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312")); string str = ""; //写标题 for (int i = 0; i < dataGridView1.ColumnCount; i++) { if (i > 0) { str += "\t"; } str +=dataGridView1.Columns[i].HeaderText; } sw.WriteLine(str); //写内容 for (int j = 0; j < dataGridView1.Rows.Count; j++) { string tempStr = ""; for (int k = 0; k < dataGridView1.Columns.Count; k++) { if (k > 0) { tempStr += "\t"; } tempStr +="'"+dataGridView1.Rows[j].Cells[k].Value.ToString(); } sw.WriteLine(tempStr); } MessageBox.Show("导出成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); sw.Close(); myStream.Close(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { //sw.Close(); //myStream.Close(); } }
这种方法速度较快。
第二种办法:通过编写公共类,然后进行调用。
类
using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Windows.Forms; using System.Reflection; using System.Runtime.InteropServices; using Microsoft.Office.Interop.Excel; namespace WindowsFormsApplication3 { class ToExcel { public static void DataGridViewToExcel(DataGridView dgv, string title) { int rowCount = dgv.RowCount; int columnCount = 0; foreach (DataGridViewColumn dHeader in dgv.Columns) { if (dHeader.Visible == true) columnCount++; } Microsoft.Office.Interop.Excel.Application exc = new Microsoft.Office.Interop.Excel.Application(); if (exc == null) { throw new Exception("Excel无法启动"); } // // Workbooks workbooks = exc.Workbooks; // _Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet); // Sheets sheets = exc.Sheets; _Worksheet worksheet = (_Worksheet)sheets[1]; if (worksheet == null) { throw new Exception("Worksheet error"); } Range r = worksheet.get_Range(exc.Cells[1, 1], exc.Cells[1, columnCount]); exc.Visible = false; r.MergeCells = true; if (r == null) { MessageBox.Show("Range无法启动"); throw new Exception("Range error"); } //以上是一些例行的初始化工作,下面进行具体的信息填充 //标题 exc.ActiveCell.FormulaR1C1 = title; exc.ActiveCell.Font.Size = 12; exc.ActiveCell.Font.Bold = true; //列头 int ColIndex = 1; foreach (DataGridViewColumn dHeader in dgv.Columns) { if (dHeader.Visible == true) worksheet.Cells[2, ColIndex++] = dHeader.HeaderText; } //填充单元格 ColIndex = 0; foreach (DataGridViewColumn col in dgv.Columns) { if (col.Visible == true) { ColIndex++; for (int i = 0; i < rowCount; i++) { if (dgv.Rows[i].Cells[col.Index].Value == null) continue; worksheet.Cells[i + 3, ColIndex] = "'"+dgv.Rows[i].Cells[col.Index].Value.ToString(); } } } exc.Cells.EntireColumn.AutoFit(); exc.Cells.VerticalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter; exc.Cells.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter; exc.Visible = true; } } }
调用代码:
private void button4_Click(object sender, EventArgs e) { if (dataGridView1.RowCount == 0) { return; } else { ToExcel.DataGridViewToExcel(dataGridView1, "学生表"); } }
这种办法可以添加上表头
第三种办法:添加一个公共类,然后进行调用,这种调用会显示存储在哪个位置,然后进行保存。
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication3 { class DataGridToExcel { public static bool DataGridviewShowToExcel(DataGridView dgv) { if (dgv.Rows.Count == 0) { MessageBox.Show("数据源为空,导出无效"); return false; } //建立Excel对象 Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.ApplicationClass(); excel.Application.Workbooks.Add(true); excel.Visible = true; //生成字段名称 for (int i = 0; i < dgv.ColumnCount; i++) { excel.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++) { excel.Cells[i + 2, j + 1] = "'" + dgv[j, i].Value.ToString(); } } return true; } } }
这种代码比较简单,导出的列默认都设置为了文本格式,避免转换保存出现数据错误。
转载于:https://blog.51cto.com/321331/1785885