码迷,mamicode.com
首页 > 其他好文 > 详细

导出到Excel

时间:2019-08-01 10:03:42      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:wro   off   RoCE   color   cti   dispose   width   数组   dialog   

//导出Excel
        public void ExportToExecl()
        {
            //System.Windows.Forms.SaveFileDialog sfd = new SaveFileDialog();
            //sfd.DefaultExt = "xls";
            string FileName = "年度旅客查验分析-" + DateTime.Now.ToString("yyyyMMddHHmmss")+".xlsx";
            //sfd.Filter = "Excel文件(*.xls)|*.xls";
            //if (sfd.ShowDialog() == DialogResult.OK)
            //{
                DoExport(SortListViewData, FileName);
            //}
        }
        /// <summary>
        /// 具体导出的方法
        /// </summary>
        /// <param name="listView">ListView</param>
        /// <param name="strFileName">导出到的文件名</param>
        private void DoExport(ListView listView, string strFileName)
        {
            try
            {
                if (listView.Items.Count == 0)
                {
                    MessageBox.Show("无数据!请先查询出数据后再进行导出操作。", "导出提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                int rowNum = listView.Items.Count;
                int columnNum = listView.Items[0].SubItems.Count;
                if (rowNum == 0 || string.IsNullOrEmpty(strFileName))
                {
                    return;
                }
                if (rowNum > 0)
                {
                    ArrayList list = new ArrayList(NewmyInspectionInfos);
                    System.Data.DataTable dt = new System.Data.DataTable();

                    DataColumn dc1 = new DataColumn(listView.Columns[0].Text, typeof(string));
                    DataColumn dc2 = new DataColumn(listView.Columns[1].Text, typeof(string));
                    DataColumn dc3 = new DataColumn(listView.Columns[2].Text, typeof(string));
                    dt.Columns.Add(dc1);
                    dt.Columns.Add(dc2);
                    dt.Columns.Add(dc3);
                    DataRow row;

                    for (int i = 0; i < list.Count; i++)
                    {
                        row = dt.NewRow();
                        row[listView.Columns[0].Text] = NewmyInspectionInfos[i].PersonnelName;
                        row[listView.Columns[1].Text] = NewmyInspectionInfos[i].Cjcs;
                        row[listView.Columns[2].Text] = NewmyInspectionInfos[i].Rjcs;
                       
                        dt.Rows.Add(row);
                    }
                    TableToExcel(dt, strFileName);
                    GC.Collect();

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出失败!错误信息:" + ex.ToString(), "导出提示");
                GC.Collect();

            }
        }

        public void TableToExcel(DataTable dt, string file)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            //设置文件标题
            saveFileDialog.Title = "导出Excel文件";
            //saveFileDialog.DefaultExt = "xls";
            //设置文件类型
            saveFileDialog.Filter = "Microsoft Office Excel 工作簿(*.xlsx)|*.xls";
            //设置默认文件类型显示顺序  
            saveFileDialog.FilterIndex = 1;
            //是否自动在文件名中添加扩展名
            saveFileDialog.AddExtension = true;
            //是否记忆上次打开的目录
            saveFileDialog.RestoreDirectory = true;
            //设置默认文件名
            saveFileDialog.FileName = file;
            IWorkbook workbook;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string localFilePath = saveFileDialog.FileName.ToString();
                string fileExt = Path.GetExtension(localFilePath).ToLower();
                if (fileExt == ".xlsx")
                {
                    workbook = new XSSFWorkbook();
                }
                else if (fileExt == ".xls")
                {
                    workbook = new HSSFWorkbook();
                }
                else
                {
                    workbook = null;
                    return;
                }
                ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName);

                //表头  
                IRow row = sheet.CreateRow(0);
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    ICell cell = row.CreateCell(i);
                    cell.SetCellValue(dt.Columns[i].ColumnName);
                }

                //数据  
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    IRow row1 = sheet.CreateRow(i + 1);
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        ICell cell = row1.CreateCell(j);
                        cell.SetCellValue(dt.Rows[i][j].ToString());
                    }
                }
                //固定列宽
                sheet.SetColumnWidth(0, 18 * 256);
                sheet.SetColumnWidth(1, 18 * 256);
                sheet.SetColumnWidth(2, 18 * 256);
                //转为字节数组  
                MemoryStream stream = new MemoryStream();
                workbook.Write(stream);
                var buf = stream.ToArray();

                //保存为Excel文件  
                FileStream fs = new FileStream(localFilePath, FileMode.Create);
                fs.Write(buf, 0, buf.Length);
                //workbook.Write(fs);
                fs.Flush();
                fs.Dispose();
                stream.Close();
                stream.Dispose();
                buf = null;
                sheet = null;
                workbook.Close();
                workbook = null;
                if (MessageBox.Show("导出成功,是否立即打开?", "导出提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start(localFilePath);
                }
                GC.Collect();//强行销毁
            }
        }

 

导出到Excel

标签:wro   off   RoCE   color   cti   dispose   width   数组   dialog   

原文地址:https://www.cnblogs.com/ganbei/p/11280365.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!