预备知识:
关于excel
workbook:工作簿,每一个xls或xlsx相当于一个工作簿。
sheet:工作表,每个工作簿可以有多个工作表。工作表相当于一张纸,工作簿相当于一个本子,将过个工作表集合在一起。
row:行
column:列
cell:单元格(表格中的最小单位,接下来导出表格就是对cell进行操作)
关于NPOI
POI:POI是一套用Java写成的库,能够帮助开发者读写xls、xlsx等格式的文件。
NPOI:POI的.net版本
XLS与XLSX:XLS是Office97-2003中表格文件使用的格式,XLSX是Office2007以后默认的表格格式。C#使用NOPI导出XLS和XLSX表格,语句是不同的。
编写程序前需要在项目的引用中添加NOPI的引用
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using System.IO;
!!!使用前需要先制作xls和xlsx各自的模板,并且需要写入的单元格不要为空
接下来是xls文件的导出
//定义excel模板路径
string xlsModelPath = System.Windows.Forms.Application.StartupPath + "\\excel\\模板.xls";
//复制要导出的excel文件
HSSFWorkbook xlsWorkBook;
//读入刚复制的要导出的excel文件
using (FileStream file = new FileStream(xlsModelPath, FileMode.Open, FileAccess.Read))
{
xlsWorkBook = new HSSFWorkbook(file);
file.Close();
}
HSSFSheet sheet1 = (HSSFSheet)xlsWorkBook.GetSheetAt(0);
//对第二行第一列、第二行第二列写入
HSSFCell cell1 = (HSSFCell)sheet1.GetRow(1).GetCell(0);
cell1.SetCellValue("博客");
HSSFCell cell2 = (HSSFCell)sheet1.GetRow(1).GetCell(1);
cell2.SetCellValue("my_clearMind");
SaveFileDialog sfd = new SaveFileDialog();
string str = System.Environment.CurrentDirectory;
sfd.InitialDirectory = str + "\\report";
sfd.FileName = "excel导出示例.xls";
sfd.Filter = "Excel 工作薄(*.xls)|*.xls";
//设置默认文件类型显示顺序
sfd.FilterIndex = 1;
//保存对话框是否记忆上次打开的目录
sfd.RestoreDirectory = true;
if (sfd.ShowDialog() == DialogResult.OK)
{
//创建文件
FileStream files = new FileStream(sfd.FileName, FileMode.Create);
xlsWorkBook.Write(files);
files.Close();
MessageBox.Show("报表生成成功!");
}
xlsx代码类似xls,其中HSSF全部替换为XSSF
string xlsxModelPath = System.Windows.Forms.Application.StartupPath + "\\excel\\模板.xlsx";
XSSFWorkbook xlsxWorkBook;
using (FileStream file = new FileStream(xlsxModelPath, FileMode.Open, FileAccess.Read))
{
xlsxWorkBook = new XSSFWorkbook(file);
file.Close();
}
XSSFSheet xsheet1 = (XSSFSheet)xlsxWorkBook.GetSheetAt(0);
XSSFCell cell1 = (XSSFCell )sheet1.GetRow(1).GetCell(0);
cell1.SetCellValue("博客");
XSSFCell cell2 = (XSSFCell)sheet1.GetRow(1).GetCell(1);
cell2.SetCellValue("my_clearMind");
SaveFileDialog sfd = new SaveFileDialog();
string str = System.Environment.CurrentDirectory;
sfd.InitialDirectory = str + "\\report";
sfd.FileName = "excel导出示例.xlsx";
sfd.Filter = "Excel 工作薄(*.xlsx)|*.xlsx";
//设置默认文件类型显示顺序
sfd.FilterIndex = 1;
//保存对话框是否记忆上次打开的目录
sfd.RestoreDirectory = true;
if (sfd.ShowDialog() == DialogResult.OK)
{
//创建文件
FileStream files = new FileStream(sfd.FileName, FileMode.Create);
xlsxWorkBook.Write(files);
files.Close();
MessageBox.Show("报表生成成功!");
}
源码下载
有用的话,记得留个评论!