C#使用POI把DataGridView中数据导出到excel文档中

时间:2021-08-17 14:44:37
 /// <summary>
        /// 把DataGridView中数据导出到excel文档中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsOutput_Click(object sender, EventArgs e)
        {
            HSSFWorkbook workbook = new HSSFWorkbook();

            //通过工作本创建一个“页”
            //HSSFSheet sheet = new HSSFSheet(workbook);
            HSSFSheet sheet = workbook.CreateSheet("第一页");

            //通过“页”创建出一个行对象
            //HSSFRow row = sheet.CreateRow(0);
            ////通过行对象,创建出一个指定为之上的列的对象
            //HSSFCell cell = row.CreateCell(0);
            ////为单元格对象,设置值,值就是从界面上取出来的
            //cell.SetCellValue(dgvMain.Rows[0].Cells[1].Value.ToString());
            ////创建第二列
            //HSSFCell cell2 = row.CreateCell(1);
            //cell2.SetCellValue(20);

            HSSFRow rowhead = sheet.CreateRow(0);
            rowhead.CreateCell(0).SetCellValue("编号");
            rowhead.CreateCell(1).SetCellValue("名称");
            rowhead.CreateCell(2).SetCellValue("性别");
            rowhead.CreateCell(3).SetCellValue("住址");
            rowhead.CreateCell(4).SetCellValue("年纪");

            //遍历面板,遍历行
            for (int rowindex = 0; rowindex < dgvMain.Rows.Count; rowindex++)
            {
                HSSFRow row = sheet.CreateRow(rowindex+1);
                //遍历面上遍历到的行的列
                for (int celIndex = 0; celIndex < 5; celIndex++)
                {
                    row.CreateCell(celIndex).SetCellValue(dgvMain.Rows[rowindex].Cells[celIndex].Value.ToString());
                }
            }

            using (SaveFileDialog sf = new SaveFileDialog())
            {
                sf.Filter = "表格|*.xls";
                sf.AddExtension = true;
                if (sf.ShowDialog() == DialogResult.OK)
                {
                    //创建一个文档流对象
                    using (FileStream fs = new FileStream(sf.FileName, FileMode.Create))
                    {
                        //将内存里面的文档对象,写入到一个文档流中
                        workbook.Write(fs);
                    }
                }
            }
        }

需在项目中添加以下dll:

C#使用POI把DataGridView中数据导出到excel文档中