教程路径:http://tonyqus.sinaapp.com/tutorial
方法一:用 NPOI 插件,该方法是生成真正的EXCEL表格,在打开EXCEL时不会弹出警告提示
View Code
using NPOI.SS.UserModel; using NPOI.HSSF.UserModel; public static void Test(DataGridView dv) { IWorkbook hssfworkbook = null; ISheet sheet = null; FileStream fs = null; string filePath = ""; SaveFileDialog file = new SaveFileDialog(); file.Filter = "*.xls|*.xls"; if (file.ShowDialog() == DialogResult.Cancel) return; filePath = file.FileName; try { hssfworkbook = new HSSFWorkbook(); sheet = hssfworkbook.CreateSheet("new sheet"); //设置默认的列宽度 sheet.DefaultColumnWidth = 17; //设置默认的行高度,但貌似没有生效? //sheet.DefaultRowHeight = 20 * 256; //生成Excel中列头名称 IRow row = sheet.CreateRow(0); for (int i = 0; i < dv.Columns.Count; i++) { //输出DataGridView列头名,注:excel第一格为1,1 row.CreateCell(i).SetCellValue(dv.Columns[i].HeaderText); } //保存数据 for (int i = 0; i < dv.Rows.Count; i++) { row = sheet.CreateRow(i + 1); for (int j = 0; j < dv.Columns.Count; j++) { string str = dv.Rows[i].Cells[j].Value.ToString(); row.CreateCell(j).SetCellValue(str); } } fs = new FileStream(filePath, FileMode.Create); hssfworkbook.Write(fs); } catch (Exception e) { MessageBox.Show(e.Message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (fs != null) fs.Close(); } }
方法二:使用 Microsoft.Office.Interop.Excel.dll 插件,该方法不是生成真正的EXCEL表格,打开的时候会弹出文件与扩展名的格式不一致的警告提示
View Code
using Microsoft.Office.Interop.Excel; public static void SaveDataToExcel(DataGridView dv) { string filePath = ""; SaveFileDialog file = new SaveFileDialog(); file.Filter = "*.xls|*.xls"; if (file.ShowDialog() == DialogResult.Cancel) return; filePath = file.FileName; Microsoft.Office.Interop.Excel.Application excel = null; Microsoft.Office.Interop.Excel.Workbook workBook = null; //导出到execl try { //没有数据的话就不往下执行 if (dv.Rows.Count <= 0) return; //实例化一个Excel.Application对象 excel = new Microsoft.Office.Interop.Excel.Application(); //新增加一个工作簿,Workbook是直接保存,不会弹出保存对话框,加上Application会弹出保存对话框,值为false会报错 workBook = excel.Application.Workbooks.Add(true); //让后台执行设置为不可见,为true的话会看到打开一个Excel,然后数据在往里写 //excel.Visible = false; //生成Excel中列头名称 for (int i = 0; i < dv.Columns.Count; i++) { //输出DataGridView列头名,注:excel第一格为1,1 excel.Cells[1, i + 1] = dv.Columns[i].HeaderText; } //保存数据 for (int i = 0; i < dv.Rows.Count; i++) { for (int j = 0; j < dv.Columns.Count; j++) { string str = dv.Rows[i].Cells[j].Value.ToString(); //"'" +是以string形式保存,所以遇到数字不会转成16进制 excel.Cells[i + 2, j + 1] = "'" + str; } } //设置禁止弹出保存和覆盖的询问提示框 excel.DisplayAlerts = false; excel.AlertBeforeOverwriting = false; workBook.Saved = true; workBook.SaveCopyAs(filePath); } catch (Exception ex) { MessageBox.Show(ex.Message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { //确保Excel进程关闭 workBook.Close(); excel.Quit(); excel = null; } }