欢迎访问 如意编程网!

如意编程网

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

winfrom导出DataGridView为Excel方法

发布时间:2024/7/5 编程问答 3 豆豆
如意编程网 收集整理的这篇文章主要介绍了 winfrom导出DataGridView为Excel方法 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

声明:此方法需要电脑安装Excel软件

需要类库:Microsoft.Office.Interop.Excel.dll 可百度自行下载

方法代码:

/// <summary>/// 导出exc/// </summary>/// <param name="dataGridView"></param>/// <param name="name">文件名字</param>public static void Import(DataGridView dataGridView,string name){string fileName = name;string saveFileName = "";SaveFileDialog saveDialog = new SaveFileDialog();saveDialog.DefaultExt = "xlsx";saveDialog.Filter = "Excel文件|*.xlsx";saveDialog.FileName = fileName;var alert= saveDialog.ShowDialog();if (alert!=DialogResult.OK){return;}saveFileName = saveDialog.FileName;Microsoft.Office.Interop.Excel.Application xlApp =new Microsoft.Office.Interop.Excel.Application();if (xlApp == null){MessageBox.Show("无法创建Excel对象,您的电脑可能未安装Excel");return;}Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;Microsoft.Office.Interop.Excel.Workbook workbook =workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);Microsoft.Office.Interop.Excel.Worksheet worksheet =(Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1 //写入标题 for (int i = 0; i < dataGridView.ColumnCount; i++){ worksheet.Cells[1, i + 1] = dataGridView.Columns[i].HeaderText; }//写入数值for (int r = 0; r < dataGridView.Rows.Count; r++){for (int i = 0; i < dataGridView.ColumnCount; i++){worksheet.Cells[r + 2, i + 1] = dataGridView.Rows[r].Cells[i].Value;}System.Windows.Forms.Application.DoEvents();}worksheet.Columns.EntireColumn.AutoFit();//列宽自适应MessageBox.Show("导出成功", "提示", MessageBoxButtons.OK);if (saveFileName != ""){try{workbook.Saved = true;workbook.SaveCopyAs(saveFileName); //fileSaved = true; }catch (Exception ex){MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);}}xlApp.Quit();GC.Collect();//强行销毁 }

 

转载于:https://www.cnblogs.com/Angel-szl/p/10525028.html

总结

以上是如意编程网为你收集整理的winfrom导出DataGridView为Excel方法的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得如意编程网网站内容还不错,欢迎将如意编程网推荐给好友。