C#导出Excel

这篇文章就教大家如何简单的用C#导出一个Excel文件,导出的功能在平时的项目开发过程中还是非常实用的。
首先我们先新建一个项目,我用的开发软件是VS2017,

1.新建一个测试项目并引入npoi

我是新建一个WPF的窗体应用程序,

 

6375263-9c49ff1155b5204f.png

image.png

 

建好项目之后,拖一个button过来。我们页面上只需要一个button就行,别的暂不需要,

 

6375263-825a3db77ab7309d.png

image.png


然后导出excel我用的是npoi,所以需要添加npoi的程序包,在VS里以此选择,工具》NuGet包管理器》解决方案的NuGet程序包,里面选择浏览,输入Npoi,选择第一个,右边勾选一下,然后选择安装即可。

6375263-1a95d7463a6711fc.png

image.png

 

安装好之后可以看到多了几个文件。

 

6375263-6f5657b7663c221c.png

image.png

2.写代码

好了接下来可以开始写带代码了。双击button进入到button的点击事件中。在cs文件中我们先引入几个命名空间。

using NPOI.SS.UserModel;
using System.IO;
using NPOI.XSSF.UserModel;

然后我们先新建一个类名字叫People

 public class People
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }

在然后写个方法,来添加一些people。

 public static List<People> Peoplelist()
        {
            List<People> peoples = new List<People>();
            for (int i = 0; i < 10; i++)
            {
                People p = new People() { ID = i + 1,Name = "名字" + i, Age = 10 + i };
                peoples.Add(p);
            }
            return peoples;
        }

接下来就需要我们点击按钮,然后把这生成的10个人,导入到excel中。导出excel的顺序,在代码里体现的就是先生成一个excel文件,然后添加一个sheet,在这个sheet里添加行,然后在行里面添加数据,
代码如下。

  private void Button_Click(object sender, RoutedEventArgs e)
        {
            List<People> peoples = Peoplelist();
            XSSFWorkbook workBook = new XSSFWorkbook();  //实例化XSSF
            XSSFSheet sheet = (XSSFSheet)workBook.CreateSheet();  //创建一个sheet

            IRow frow0 = sheet.CreateRow(0);  // 添加一行(一般第一行是表头)
            frow0.CreateCell(0).SetCellValue("序号");
            frow0.CreateCell(1).SetCellValue("姓名");
            frow0.CreateCell(2).SetCellValue("年龄");   //表头内容

            for (int i = 0; i < peoples.Count; i++)  //循环添加list中的内容放到表格里
            {
                IRow frow1 = sheet.CreateRow(i+1);  //之所以从i+1开始 因为第一行已经有表头了
                frow1.CreateCell(0).SetCellValue(peoples[i].ID);
                frow1.CreateCell(1).SetCellValue(peoples[i].Name);
                frow1.CreateCell(2).SetCellValue(peoples[i].Age);
            }
            string saveFileName = "E:\\" + "Excel\\" + "people" + ".xlsx";
            try
            {
                using (FileStream fs = new FileStream(saveFileName, FileMode.Create, FileAccess.Write))
                {
                    workBook.Write(fs);  //写入文件
                    workBook.Close();  //关闭
                }
                MessageBox.Show("导出成功");
            }
            catch (Exception)
            {
                workBook.Close();
            }
        }

因为我是直接把文件放到E盘下一个Excel文件夹下,所以我提前建好了这个文件夹。接下来就可以看到点击导出按钮之后,在Excel 文件夹中,出现了一个people.xlsx文件,双击打开,看到里面已经有数据了。

 

6375263-85b2ea8a66b9d882.png

image.png

 

这只是一个非常简单的导出excel方法,对里面的样式等都没有做修改,在以后的工作中,可能需要的合并单元格,设置单元格样式,以及插入图片,数值计算等操作,慢慢来熟悉每一行代码,相信自己可以做的更好。
这篇文章就讲这么多,下一篇文章可以教大家如何导入excel。
Study hard and make progress every day.

更多学习资料请关注"爱游戏爱编程"。

 

6375263-578835b1e5aa99fa.jpg

爱游戏爱编程.jpg

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
/// <summary> /// 导出Excel /// </summary> /// <param name="table"></param> /// <returns></returns> public bool ToExcel(DataTable table) { FileStream fs = new FileStream(this._filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); IWorkbook workBook = new HSSFWorkbook(); this._sheetName = this._sheetName.IsEmpty() ? "sheet1" : this._sheetName; ISheet sheet = workBook.CreateSheet(this._sheetName); //处理表格标题 IRow row = sheet.CreateRow(0); row.CreateCell(0).SetCellValue(this._title); sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, table.Columns.Count - 1)); row.Height = 500; ICellStyle cellStyle = workBook.CreateCellStyle(); IFont font = workBook.CreateFont(); font.FontName = "微软雅黑"; font.FontHeightInPoints = 17; cellStyle.SetFont(font); cellStyle.VerticalAlignment = VerticalAlignment.Center; cellStyle.Alignment = HorizontalAlignment.Center; row.Cells[0].CellStyle = cellStyle; //处理表格列头 row = sheet.CreateRow(1); for (int i = 0; i < table.Columns.Count; i++) { row.CreateCell(i).SetCellValue(table.Columns[i].ColumnName); row.Height = 350; sheet.AutoSizeColumn(i); } //处理数据内容 for (int i = 0; i < table.Rows.Count; i++) { row = sheet.CreateRow(2 + i); row.Height = 250; for (int j = 0; j < table.Columns.Count; j++) { row.CreateCell(j).SetCellValue(table.Rows[i][j].ToString()); sheet.SetColumnWidth(j, 256 * 15); } } //写入数据流 workBook.Write(fs); fs.Flush(); fs.Close(); return true; } /// <summary> /// 导出Excel /// </summary> /// <param name="table"></param> /// <param name="title"></param> /// <param name="sheetName"></param> /// <returns></returns> public bool ToExcel(DataTable table, string title, string sheetName, string filePath) { this._title = title; this._sheetName = sheetName; this._filePath = filePath; return ToExcel(table); }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李公子lm

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值