将ListView中的记录导出为Excel

        public static bool ExportExcel(ListView lvExport)
        {
            string saveFileName = "";
            bool fileSaved = false;
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.DefaultExt = "xls";
            saveDialog.Filter = "Excel文件|*.xls";
            saveDialog.FileName = "Sheet1";
            if (saveDialog.ShowDialog() != DialogResult.OK)
                return false;
            saveFileName = saveDialog.FileName;
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

            if (xlApp == null)
            {
                MessageBox.Show("无法创建Excel对象,可能您的PC上未安装Excel");
                return false;
            }
            Workbooks workbooks = xlApp.Workbooks;
            Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
            Worksheet worksheet = (Worksheet)workbook.Worksheets[1];//取得sheet1
            //写入字段
            for (int i = 0; i < lvExport.Columns.Count; i++)
            {
                worksheet.Cells[1, i + 1] = lvExport.Columns[i].Text;
            }
            //写入数值

            for (int r = 0; r < lvExport.Items.Count; r++)
            {
                for (int i = 0; i < lvExport.Columns.Count; i++)
                {
                    if (lvExport.Items[r].SubItems[i] != null)
                        worksheet.Cells[r + 2, i + 1] = lvExport.Items[r].SubItems[i].Text;
                }
                System.Windows.Forms.Application.DoEvents();
            }
            worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。
            if (saveFileName != "")
            {
                try
                {
                    workbook.Saved = true;
                    workbook.SaveCopyAs(saveFileName);
                    fileSaved = true;
                }
                catch (Exception ex)
                {
                    fileSaved = false;
                    MessageBox.Show("导出文件时出错,文件可能正被打开!/n" + ex.Message);
                }
            }
            else
            {
                fileSaved = false;
            }
            xlApp.Quit();
            GC.Collect();//强行销毁
            if (fileSaved && System.IO.File.Exists(saveFileName))
                System.Diagnostics.Process.Start(saveFileName);
            return true;
        }

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页