zoukankan      html  css  js  c++  java
  • WinForm中DataGridView导出为Excel(快速版)

            public static void ExportExcel(DataGridView myDGV, string fileName)
            {
                string saveFileName = fileName;
                //SaveFileDialog saveDialog = new SaveFileDialog();
                //saveDialog.DefaultExt = "xls";
                //saveDialog.Filter = "Excel文件|*.xls";
                //saveDialog.FileName = fileName;
                //saveDialog.ShowDialog();
                //saveFileName = saveDialog.FileName;
                if (saveFileName.IndexOf(":") < 0) return; //被点了取消
                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 < myDGV.ColumnCount; i++)
                {
                    worksheet.Cells[1, i + 1] = myDGV.Columns[i].HeaderText;
                }
                //写入数值
                for (int r = 0; r < myDGV.Rows.Count; r++)
                {
                    for (int i = 0; i < myDGV.ColumnCount; i++)
                    {
                        worksheet.Cells[r + 2, i + 1] = myDGV.Rows[r].Cells[i].Value;
                    }
                    System.Windows.Forms.Application.DoEvents();
                }
                worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
                if (saveFileName != "")
                {
                    try
                    {
                        workbook.Saved = true;
                        workbook.SaveCopyAs(saveFileName);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("导出文件时出错,文件可能正被打开!
    " + ex.Message);
                    }
                }
                xlApp.Quit();
                GC.Collect();//强行销毁
                MessageBox.Show("文件: " + fileName + ".xls 保存成功", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
  • 相关阅读:
    JSE-1.1.4 内存屏障和CPU缓存
    Ajax
    R手册(Common)--R6 and S4
    掌握 小程序项目新建后的 初始代码 及 git远程管理(2)
    微信小程序 网课学习笔记 开发前的准备工作(1)
    vuex中action如何互相调用
    ajax请求时,请求路径自动拼上页面路径?
    10个免费的CDN
    java面向对象
    java中方法的递归调用
  • 原文地址:https://www.cnblogs.com/ilookbo/p/4069103.html
Copyright © 2011-2022 走看看