C#操作Excel方法有很多,以前用的需要电脑安装office才能用,但因为版权问题公司不允许安装office。所以改用NPOI进行Excel操作,基本上一些简单的Excel操作都没有问题,读写合并单元格等都能实现。
命名空间:
using NPOI;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
简单的保存数据:
public void ExcelTest(string path)
{
IWorkbook workbook = new HSSFWorkbook();//创建Workbook
workbook.CreateSheet("sheet1");//创建sheet
using (FileStream fs = File.Create(path))//path=mmm.xls;
{
ISheet sheet = workbook.GetSheetAt(0);//获取sheet
sheet.CreateRow(1).CreateCell(0).SetCellValue("nami");//创建第一行/创建第一单元格/设置第一单元格的内容[可以分开创建,但必须先创建行才能创建单元格不然报错]
sheet.GetRow(1).CreateCell(1).SetCellValue("robin");//获取第一行/创建第二单元格/设置第二单元格的内容
sheet.CreateRow(2).CreateCell(0).SetCellValue("saber");//创建第二行/创建第一单元格/设置第一单元格的内容
sheet.GetRow(2).CreateCell(1).SetCellValue("luffy");//获取第二行/创建第二单元格/设置第二单元格的内容
sheet.GetRow(1).CreateCell(2).SetCellValue(5);
sheet.GetRow(2).CreateCell(2).SetCellValue(2);
//添加批注
IDrawing draw = sheet.CreateDrawingPatriarch();
IComment comment = draw.CreateCellComment(new HSSFClientAnchor(0, 0, 0, 0, 1, 2, 4, 4));//里面参数应该是指示批注的位置大小吧
comment.String = new HSSFRichTextString("one-piece");//添加批注内容
comment.Author = "梦琪小生";//添加批注作者
sheet.GetRow(1).GetCell(1).CellComment = comment;//将之前设置的批注给定某个单元格
//单元格格式设置
ICellStyle cellStyle = workbook.CreateCellStyle();
IDataFormat format = workbook.CreateDataFormat();
cellStyle.DataFormat = format.GetFormat("0.00");
sheet.GetRow(2).GetCell(2).CellStyle = cellStyle;
//合并单元格
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 2));
sheet.CreateRow(0).CreateCell(0).SetCellValue("梦琪小生");
ICellStyle titleStyle = workbook.CreateCellStyle();
IFont titleFont = workbook.CreateFont();
titleFont.FontHeightInPoints = 15;//设置字体大小
titleFont.Color = HSSFColor.BLUE.index;//设置字体颜色
titleStyle.SetFont(titleFont);
titleStyle.Alignment = HorizontalAlignment.CENTER;//居中
sheet.GetRow(0).GetCell(0).CellStyle = titleStyle;
ICellStyle style = workbook.CreateCellStyle();
style.BorderBottom = BorderStyle.THIN;
style.BorderLeft = BorderStyle.THIN;
style.BorderRight = BorderStyle.THIN;
style.BorderTop = BorderStyle.THIN;
sheet.GetRow(1).GetCell(1).CellStyle = style;
//插入图片
HSSFClientAnchor anchor2 = new HSSFClientAnchor(0, 0, 0, 0, 0, 5, 6, 10);
byte[] bytes = System.IO.File.ReadAllBytes(@"C:\Users\Administrator\Desktop\image\mqxs.png");
int picID = workbook.AddPicture(bytes, PictureType.PNG);
IPicture pic = patriarch.CreatePicture(anchor2, picID);
pic.Resize();
workbook.Write(fs);//保存文件
}
}
读取Excel返回DataTable:
<