在Winform中使用NPOI第三方组件导出Excel

最近使用NPOI导出Datagridview数据。。。。。。


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using DLZY;
using NPOI;
using NPOI.POIFS;
using NPOI.HSSF;
using NPOI.HPSF;
using NPOI.Util;
using NPOI.HSSF.UserModel;
using NPOI.POIFS.FileSystem;
using System.IO;
using NPOI.SS.UserModel;
using Model;
using DAL;


namespace 收入查询
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }


        private void Form2_Load(object sender, EventArgs e)
        {


        }


        private void Bind()
        {
            SqlConnection conn = SqlHelper.Conn(); //连接数据库
            //string sql = string.Format("select * from Income_Note where IncomeType ='{0}' and  IncomeTime   between '{1}' and '{2}'", srtype.Text, Convert.ToDateTime(kstime.Text), Convert.ToDateTime(jstime.Text));
            string sql = "select * from Income_Note where IncomeType =@IncomeType and  IncomeTime  between  @Start  and @End ";
            SqlDataAdapter ad = new SqlDataAdapter(sql, conn); //提交查询命令
            ad.SelectCommand.Parameters.AddWithValue("@IncomeType", srtype.Text);
            ad.SelectCommand.Parameters.AddWithValue("@Start", Convert.ToDateTime(kstime.Text));
            ad.SelectCommand.Parameters.AddWithValue("@End", Convert.ToDateTime(jstime.Text));
            DataTable dt = new DataTable(); //新建表
            ad.Fill(dt);
            srdata.DataSource = dt;// 显示收入查询返回的dt表结果到。。。
        }


        private void button1_Click(object sender, EventArgs e)
        {
            if (srtype.Text.Trim() != string.Empty)
            {
                Bind();
            }
            else
            {
                MessageBox.Show("信息有误,请输入正确的的值!");
            }
        }


        private void button3_Click(object sender, EventArgs e)
        {
             Form3 frm3= new Form3();
            frm3.ShowDialog();
        }


        private void button4_Click(object sender, EventArgs e)
        {


            if (srdata.SelectedRows.Count == 0)
            {
                MessageBox.Show("没有选择有效行");
                return;
            }
            else if (MessageBox.Show("你确定要删除吗?", "警告", MessageBoxButtons.YesNoCancel) == DialogResult.Yes)
            {
                
                    SqlConnection conn = SqlHelper.Conn();
                    conn.Open();
                    string sql = "delete from Income_Note where IncomeId=@id";
                    SqlCommand comm = new SqlCommand(sql, conn);
                    comm.Parameters.AddWithValue("id", srdata.SelectedRows[0].Cells["colid"].Value.ToString());
                    comm.ExecuteNonQuery();
                    conn.Close();
                    Bind();
                    MessageBox.Show("删除成功");
            }
            else
            {
                return;
            }


          
        }


        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        private void btnExport_Click(object sender, EventArgs e)
        {
            //ExportTOExcel(srdata);
            SaveFileDialog sdfexport = new SaveFileDialog();
            sdfexport.Filter = "Excel文件|*.xls";
            if (sdfexport.ShowDialog() == DialogResult.No)
            {
                return;
            }
            string filename = sdfexport.FileName;
            HSSFWorkbook workbook = new HSSFWorkbook();
            ISheet sheet = workbook.CreateSheet("支出数据");
            IRow rowHeader = sheet.CreateRow(0);
            rowHeader.CreateCell(0, CellType.STRING).SetCellValue("ID");
            rowHeader.CreateCell(1, CellType.STRING).SetCellValue("用户姓名");
            rowHeader.CreateCell(2, CellType.STRING).SetCellValue("收入方式");
            rowHeader.CreateCell(3, CellType.STRING).SetCellValue("收入时间");
            rowHeader.CreateCell(4, CellType.STRING).SetCellValue("收入金额");
            rowHeader.CreateCell(5, CellType.STRING).SetCellValue("备注");
            sheet.SetColumnWidth(3, 20 * 256);
          
            
            string sql = "select * from Income_Note where IncomeType =@IncomeType and  IncomeTime  between  @Start  and @End ";
            List<SqlParameter> paramsList = new List<SqlParameter>();
            paramsList.Add(new SqlParameter("@IncomeType", srtype.Text));
            paramsList.Add(new SqlParameter("@Start", Convert.ToDateTime(kstime.Text)));
            paramsList.Add(new SqlParameter("@End", Convert.ToDateTime(jstime.Text)));






            Income_Note[] incomenotes = new IncomeNoteDAL().Search(sql, paramsList);
           
            for (int i = 0; i < incomenotes.Length; i++)
            {
                Income_Note incomenote = incomenotes[i];
                IRow row = sheet.CreateRow(i + 1);
                row.CreateCell(0, CellType.NUMERIC).SetCellValue(incomenote.IncomeId);
                row.CreateCell(1, CellType.STRING).SetCellValue(incomenote.UserName);
                row.CreateCell(2, CellType.STRING).SetCellValue(incomenote.IncomeType);


                ICellStyle styledate = workbook.CreateCellStyle();
                IDataFormat format = workbook.CreateDataFormat();
                styledate.DataFormat = format.GetFormat("yyyy\"年\"m\"月\"d\"日\"");
                
                ICell cellDate = row.CreateCell(3, CellType.NUMERIC);
                
                cellDate.CellStyle = styledate;
                cellDate.SetCellValue(incomenote.IncomeTime);




               
                HSSFCellStyle cellStyle2 = (HSSFCellStyle)workbook.CreateCellStyle(); 
                HSSFDataFormat format2 = (HSSFDataFormat)workbook.CreateDataFormat(); 
                //cellStyle2.DataFormat = format2.GetFormat("¥#,##0");
                cellStyle2.DataFormat = format2.GetFormat("¥#,##0;¥-#,##0");
                
                HSSFCell cellMoney = (HSSFCell)row.CreateCell(4, CellType.NUMERIC);
                cellMoney.CellStyle = cellStyle2;


                cellMoney.SetCellValue(incomenote.IncomeMoney.ToString());


                




                row.CreateCell(5, CellType.STRING).SetCellValue(incomenote.IncomeNote);
            }


            using (Stream stream = File.OpenWrite(filename))
            {
                workbook.Write(stream);
            }
        }

    }
}


截图如下所示:

导出xsl如下:

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 使用NPOI可以很方便地在Winform应用程序导出Excel文件。 首先,我们需要将NPOI引用添加到Winform项目。可以通过NuGet包管理器或手动引用方式添加。 然后,我们需要创建一个工作簿对象,并添加一个工作表。可以使用HSSFWorkbook或XSSFWorkbook类来创建工作簿对象,分别对应xls和xlsx格式的Excel文件。 接下来,我们可以向工作表添加数据。可以使用工作表的创建行对象,然后为每行添加单元格数据。可以设置单元格的值、格式、样式等属性。 最后,我们需要将工作簿保存为Excel文件。可以使用FileStream类创建一个文件流对象,并使用工作簿的Write方法将数据写入到文件流。 以下是一个简单的示例代码,将一个包含学生信息的列表导出Excel文件: ```csharp using System; using System.Collections.Generic; using System.IO; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; // 创建工作簿和工作表 HSSFWorkbook workbook = new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet("学生信息"); // 添加表头 IRow headerRow = sheet.CreateRow(0); headerRow.CreateCell(0).SetCellValue("学号"); headerRow.CreateCell(1).SetCellValue("姓名"); headerRow.CreateCell(2).SetCellValue("年龄"); // 添加数据 List<Student> students = GetStudents(); for (int i = 0; i < students.Count; i++) { IRow dataRow = sheet.CreateRow(i + 1); dataRow.CreateCell(0).SetCellValue(students[i].Id); dataRow.CreateCell(1).SetCellValue(students[i].Name); dataRow.CreateCell(2).SetCellValue(students[i].Age); } // 保存为Excel文件 using (FileStream fileStream = new FileStream("学生信息.xls", FileMode.Create)) { workbook.Write(fileStream); } ``` 在这个示例,我们首先创建了一个工作簿和一个工作表,并添加了表头。然后,通过获取学生信息列表来添加数据。最后,我们将工作簿保存为名为“学生信息.xls”的Excel文件。 这样,使用NPOI就可以在Winform应用程序导出Excel文件。希望可以对你有所帮助! ### 回答2: 使用WinForm搭配NPOI导出Excel非常简单。首先,我们需要在WinForm添加对NPOI的引用。可以通过NuGet包管理器来导入NPOI库。 导入库后,我们可以创建一个DataGridView控件来展示需要导出的数据,或者直接在代码定义一个DataTable对象来储存数据。然后,在按钮的Click事件处理程序编写导出Excel的代码。 以下是一个简单的示例: 1. 添加一个DataGridView控件(或创建DataTable对象)并加载需要导出的数据。 2. 在按钮的Click事件添加以下代码: ```csharp using NPOI.XSSF.UserModel; // 导入XSSF命名空间 using NPOI.SS.UserModel; // 导入SS命名空间 using NPOI.HSSF.Util; // 导入HSSFUtil命名空间 using NPOI.HSSF.UserModel; // 导入HSSFUserModel命名空间 using NPOI.SS.Util; // 导入SSUtil命名空间 using NPOI.HPSF; // 导入HPSF命名空间 using NPOI.POIFS.FileSystem; // 导入POIFS命名空间 // 创建一个Excel文档对象 XSSFWorkbook workbook = new XSSFWorkbook(); // 创建一个工作表对象 ISheet sheet = workbook.CreateSheet("Sheet1"); // 创建行和单元格 IRow row = sheet.CreateRow(0); for (int i = 0; i < dataGridView1.Columns.Count; i++) { row.CreateCell(i).SetCellValue(dataGridView1.Columns[i].HeaderText); } // 填充数据 for (int i = 0; i < dataGridView1.Rows.Count; i++) { row = sheet.CreateRow(i + 1); for (int j = 0; j < dataGridView1.Columns.Count; j++) { row.CreateCell(j).SetCellValue(dataGridView1.Rows[i].Cells[j].Value.ToString()); } } // 保存文件 SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Excel文件|*.xlsx"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { using (FileStream fs = new FileStream(saveFileDialog.FileName, FileMode.Create)) { workbook.Write(fs); } } // 提示导出成功 MessageBox.Show("导出成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); ``` 这是一个基本的WinForm使用NPOI导出Excel的代码示例。你可以根据自己的需求进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值