一、概述

  Apache POI是Apache软件基金会的开源项目,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。 .NET的开发人员则可以利用NPOI (POI for .NET) 来存取 Microsoft Office文档的功能。

1.1、POI结构说明

包名称说明

  HSSF提供读写Microsoft Excel XLS格式档案的功能。

  XSSF提供读写Microsoft Excel OOXML XLSX格式档案的功能。

  HWPF提供读写Microsoft Word DOC格式档案的功能。

  HSLF提供读写Microsoft PowerPoint格式档案的功能。

  HDGF提供读Microsoft Visio格式档案的功能。

  HPBF提供读Microsoft Publisher格式档案的功能。

  HSMF提供读Microsoft Outlook格式档案的功能。

二、POI对于excel使用

2.1、创建一个excel

    //创建 2003 excel 格式 xls
@Test
public void test() throws Exception {
Workbook workbook=new HSSFWorkbook();//定义一个工作薄
workbook.createSheet("sheet1");//需要默认创建一个sheet,否则打开时候报错
FileOutputStream out= new FileOutputStream("test.xls");
workbook.write(out);
out.close();
}
//创建 2007 以后的excel格式 xlsx
@Test
public void test2() throws Exception {
Workbook workbook=new XSSFWorkbook();//定义一个工作薄
workbook.createSheet("sheet1");//需要默认创建一个sheet,否则打开时候报错
FileOutputStream out= new FileOutputStream("test.xlsx");
workbook.write(out);
out.close();
}

2.2、基本的使用

    // 基本测试 创建一个sheet 一行 几列数据
@Test
public void testBase() throws Exception {
Workbook wk=new HSSFWorkbook();//创建一个工作薄
Sheet sh=wk.createSheet("第一个sheet页");//创建一个sheet页
Row row=sh.createRow(0);//创建第一行
Cell cell=row.createCell(0);//创建第一行的第一个单元格
cell.setCellValue(1);//为第一行第一个单元格塞值
row.createCell(1).setCellValue(1.2);//创建第一行第2个单元格并赋值
row.createCell(2).setCellValue("这是一个字符串");//创建第一行第3个单元格并赋值
row.createCell(3).setCellValue(true);//创建第一行第4个单元格并赋值
FileOutputStream out= new FileOutputStream("cells和sheet页.xls");
wk.write(out);
out.close();
}

效果

  

2.3、单元格操作

2.3.1、设置单元格边框颜色

    // 设置单元格边框 颜色
@Test
public void testCellBorderColor() throws Exception {
Workbook wb=new HSSFWorkbook();//创建工作簿
Sheet sh=wb.createSheet("第一个sheet页");//创建一个sheet页
Row row=sh.createRow(2);//创建一行
Cell cell=row.createCell(2);//创建一个单元格
cell.setCellValue(4);//设置值
CellStyle cellStyle=wb.createCellStyle();
cellStyle.setBorderBottom(BorderStyle.THIN);//设置底部边框
cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());//设置底部边框颜色
cellStyle.setBorderLeft(BorderStyle.THIN);//设置左部边框
cellStyle.setLeftBorderColor(IndexedColors.BLUE.getIndex());//设置左部边框颜色
cellStyle.setBorderRight(BorderStyle.THIN);//设置右部边框
cellStyle.setRightBorderColor(IndexedColors.RED.getIndex());//设置右部边框颜色
cellStyle.setBorderTop(BorderStyle.THIN);//设置顶部边框
cellStyle.setTopBorderColor(IndexedColors.ORANGE.getIndex());//设置顶部边框颜色
cell.setCellStyle(cellStyle);
FileOutputStream out=new FileOutputStream("test.xls");
wb.write(out);
out.close();
}

  

2.3.2、单元格数据格式展示【string、number、日期、布尔】

    @Test
public void testDiffCell() throws Exception {
Workbook wk = new HSSFWorkbook();//创建工作薄
Sheet sh = wk.createSheet();//创建sheet页
Row row = sh.createRow(0);//创建第一行
row.createCell(0).setCellValue(1);
row.createCell(1).setCellValue("字符串");
row.createCell(2).setCellValue(true);
//1、日期默认为 数值
row.createCell(3).setCellValue(new Date()); row.createCell(4).setCellValue(HSSFCell.ENCODING_COMPRESSED_UNICODE);
row.createCell(5).setCellValue(false);
//2、日期变成字符串
row.createCell(6).setCellValue("2019-07-19"); //3、单元格设置日期类型样式
// 定义Cell格式
CellStyle cellStyle = wk.createCellStyle();
CreationHelper creationHelper = wk.getCreationHelper();
cellStyle.setDataFormat(
creationHelper.createDataFormat().getFormat("yyyy-MM-dd hh:mm:ss")
); Cell cell = row.createCell(7);//创建一个单元格
cell.setCellValue(new Date()); // 插入格式化日期
cell.setCellStyle(cellStyle); cell = row.createCell(8); // 插入格式化日期
cell.setCellValue(Calendar.getInstance());
cell.setCellStyle(cellStyle); FileOutputStream out = new FileOutputStream("test.xls");
wk.write(out);
out.close();
}

  

2.3.3、字体处理

    @Test
public void testFont() throws Exception {
Workbook workbook=new HSSFWorkbook();
Sheet sheet=workbook.createSheet();
Row row=sheet.createRow(1);
//字体处理类
Font font=workbook.createFont();
font.setFontHeightInPoints((short)18);//设置字体高度
font.setItalic(true);//字体是否是斜体
font.setFontName("Courier New");//设置字体名字 CellStyle cellStyle=workbook.createCellStyle();
cellStyle.setFont(font);
Cell cell=row.createCell(1);
cell.setCellValue("This is test fonts");
cell.setCellStyle(cellStyle); FileOutputStream out=new FileOutputStream("testFont.xls");
workbook.write(out);
out.close();

  

2.3.4、读取写入

    @Test
public void testRead() throws Exception {
InputStream inputStream=new FileInputStream("/Users/lihongxu6/IdeaProjects/common/common-help/test.xls");//创建一个输入流读取单元格
POIFSFileSystem fileSystem=new POIFSFileSystem(inputStream);//包装类,将读取的内容放入内存中
Workbook wb=new HSSFWorkbook(fileSystem);
Sheet sheet=wb.getSheetAt(0);//获取第一个sheet页
Row row=sheet.getRow(0);//获取第一行
Cell cell=row.getCell(0);//获取第一个单元格
if(cell == null||"".equals(cell)) {
cell=row.createCell(3);
}
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue("测试单元格"); FileOutputStream out=new FileOutputStream("test.xls");
wb.write(out);
out.close();
inputStream.close();
}

   →  

2.3.5、数据格式化

    @Test
public void testDataStyle() throws Exception {
Workbook workbook=new HSSFWorkbook();
Sheet sheet=workbook.createSheet("第一个sheet页");
CellStyle style;
DataFormat format=workbook.createDataFormat();
Row row;
Cell cell; short rowNum=0;
short cellNume=1; row=sheet.createRow(rowNum++);
cell=row.createCell(cellNume);
cell.setCellValue(111111.25); style=workbook.createCellStyle();
style.setDataFormat(format.getFormat("0.0"));
cell.setCellStyle(style); row=sheet.createRow(rowNum++);
cell=row.createCell(cellNume);
cell.setCellValue(11111111.25); style=workbook.createCellStyle();
style.setDataFormat(format.getFormat("#,##0.000"));
cell.setCellStyle(style); FileOutputStream out=new FileOutputStream("testDataStyle.xls");
workbook.write(out);
out.close();
}

  

2.3.6、文本提取

    @Test
public void testText() throws Exception {
InputStream in= new FileInputStream("/Users/lihongxu6/IdeaProjects/common/common-help/test.xls");
POIFSFileSystem pfs=new POIFSFileSystem(in);
HSSFWorkbook hwb=new HSSFWorkbook(pfs);
ExcelExtractor excelExtractor=new ExcelExtractor(hwb);//提取文本
excelExtractor.setIncludeSheetNames(false);//不需要sheet页名字
System.out.println(excelExtractor.getText());
in.close();
}

输出

测试单元格    字符串    true    43665.45162    0    false    2019-07-19    2019-07-19  10:50:20    2019-07-19  10:50:20

2.3.7、遍历数据

    @Test
public void testItor() throws Exception { InputStream in= new FileInputStream("/Users/lihongxu6/IdeaProjects/common/common-help/test.xls");
POIFSFileSystem pfs=new POIFSFileSystem(in);//文件系统可接受一个输入流
HSSFWorkbook hwb=new HSSFWorkbook(pfs);
HSSFSheet sheet=hwb.getSheetAt(0);//获取第一个sheet页
if(sheet == null) {
return;
}
//遍历row
for(int rowNum= 0;rowNum <= sheet.getLastRowNum();rowNum++) {
HSSFRow hssfRow=sheet.getRow(rowNum);
if(hssfRow== null) {
continue;
}
//遍历cells
for(int cellNum=0;cellNum <= hssfRow.getLastCellNum();cellNum++) {
HSSFCell hssfcell=hssfRow.getCell(cellNum);
if(hssfcell== null) {
continue;
}
System.out.print(" "+getValue(hssfcell));
}
System.out.println();
}
in.close();
}
/**
* 判断cell的数据格式
* @param hssfcell
* @return
*/
private static String getValue(HSSFCell hssfcell) {
if(hssfcell.getCellType() ==HSSFCell.CELL_TYPE_BOOLEAN ) {
return String.valueOf(hssfcell.getBooleanCellValue());
}else if(hssfcell.getCellType() ==HSSFCell.CELL_TYPE_NUMERIC ) {
return String.valueOf(hssfcell.getNumericCellValue());
}else {
return String.valueOf(hssfcell.getStringCellValue());
}
}

输出

测试单元格 字符串 true 43665.45161912037 0.0 false 2019-07-19 43665.45162721065 43665.45162721065

2.3.8、单元格对齐方式

    @Test
public void testAlign() throws Exception {
Workbook wb=new HSSFWorkbook();//创建工作薄
Sheet sh=wb.createSheet();//创建sheet页
Row row=sh.createRow(2);//创建一行
row.setHeightInPoints(30);//设置行高 createCell(wb,row,(short)0,HorizontalAlignment.CENTER,VerticalAlignment.BOTTOM);
createCell(wb,row,(short)1,HorizontalAlignment.CENTER_SELECTION,VerticalAlignment.CENTER);
createCell(wb,row,(short)2,HorizontalAlignment.FILL,VerticalAlignment.JUSTIFY);
createCell(wb,row,(short)3,HorizontalAlignment.GENERAL,VerticalAlignment.TOP);
FileOutputStream out=new FileOutputStream("testAlign.xls");
wb.write(out);
out.close();
} /**
* 设置单元格对齐方式
* @param wb 工作薄
* @param row 行
* @param column 列
* @param halign 水平
* @param valign 垂直
*/
private static void createCell(Workbook wb,Row row,short column,HorizontalAlignment halign,VerticalAlignment valign) {
Cell cells=row.createCell(column);//创建单元格
cells.setCellValue(new HSSFRichTextString("Align it"));//设置值
CellStyle cellstyle=wb.createCellStyle();//创建单元格样式
cellstyle.setAlignment(halign);//设置单元格水平方向对齐方式
cellstyle.setVerticalAlignment(valign);//设置单元格垂直方向对齐方式
cells.setCellStyle(cellstyle);//设置单元格样式
}

  

2.3.9、单元格背景色

    @Test
public void testBg() throws Exception {
Workbook wb=new HSSFWorkbook();
Sheet sheet=wb.createSheet("第一个Sheet页");
Row row=sheet.createRow(2); Cell cell=row.createCell(1);
cell.setCellValue("xx");
CellStyle cellStyle=wb.createCellStyle();
cellStyle.setFillBackgroundColor(IndexedColors.GREEN.getIndex());//前景色
cellStyle.setFillPattern(FillPatternType.BIG_SPOTS);
cell.setCellStyle(cellStyle); Cell cell2=row.createCell(3);
cell2.setCellValue("yy");
CellStyle cellStyle2=wb.createCellStyle();
cellStyle2.setFillForegroundColor(IndexedColors.PINK.getIndex());//背景色
cellStyle2.setFillPattern(FillPatternType.SPARSE_DOTS);
cell2.setCellStyle(cellStyle2); FileOutputStream out=new FileOutputStream("testBg.xls");
wb.write(out);
out.close();
}

  

2.3.9、单元格换行

    @Test
public void testLine() throws Exception {
Workbook workbook=new HSSFWorkbook();
Sheet sheet=workbook.createSheet();
Row row=sheet.createRow(0);
Cell cell=row.createCell(2);
cell.setCellValue("我要换行了\n有没有成功?"); CellStyle cellStyle=workbook.createCellStyle();
cellStyle.setWrapText(true);//设置可以换行
cell.setCellStyle(cellStyle); row.setHeightInPoints(2*sheet.getDefaultRowHeightInPoints());//设置2倍的行高
sheet.autoSizeColumn(2);//设置单元格宽度 FileOutputStream out=new FileOutputStream("testLine.xls");
workbook.write(out);
out.close();
}

  

2.3.10、单元格合并居中

    @Test
public void testSpan() throws Exception {
Workbook wb=new HSSFWorkbook();//创建工作薄
Sheet sheet=wb.createSheet();//创建sheet页
Row row=sheet.createRow(1);//创建行 Cell cell=row.createCell(1);//创建单元格
cell.setCellValue("单元格合并测试");
/**
* 合并单元格的API
*/
sheet.addMergedRegion(new CellRangeAddress(
1,//起始行
2,//结束行
1,//起始列
2//结束列
));
CellStyle cellStyle=wb.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
cell.setCellStyle(cellStyle); FileOutputStream out=new FileOutputStream("testSpan.xls");
wb.write(out);
out.close();
}

  

001-poi-excel-基础、单元格使用操作的更多相关文章

  1. C#实现对EXCEL指定单元格进行操作

    using System; using System.Collections.Generic; using System.Text; using Microsoft.Office.Interop.Ex ...

  2. POI/Excel/HTML单元格公式问题

    一.问题描述 使用MyBatis从数据库中获取数据,然后用POI把数据填充到Excel模板中,生成最终的xls文件.把最终的xls文件转换为html文件,并返回给前台显示在Panel中. Excel模 ...

  3. poi excel 合并单元格

    结论:final CellRangeAddress cra = new CellRangeAddress(rowId, rowId + rowSkip,        colId, colId + c ...

  4. ASP.NET 导出gridview中的数据到Excel表中,并对指定单元格换行操作

    1. 使用NPOI读取及生成excel表. (1)导出Click事件: 获取DataTable; 给文件加文件名: string xlsxName = "xxx_" + DateT ...

  5. [从产品角度学EXCEL 03]-单元格的秘密

    这是<从产品角度学EXCEL>系列——单元格的秘密. 前言请看: 0 为什么要关注EXCEL的本质 1 EXCEL是怎样运作的 2 EXCEL里的树形结构 或者你可以去微信公众号@尾巴说数 ...

  6. POI按照源单元格设置目标单元格格式

    原文:http://jjw198874.blog.163.com/blog/static/1889845522011102401854234/ POI按照源单元格设置目标单元格格式 poi按照一个源单 ...

  7. POI设置excle单元格样式

    Java利用POI生成Excel强制换行 使用POI创建一个简单的   myXls.xls   文件       常用的包为   org.apache.poi.hssf.usermodel.*;    ...

  8. Excel的单元格设置下拉选项并填充颜色

    如何在Excel的单元格中加入下拉选项   方法/步骤     第一步:打开excel文档,选中需加入下拉选项的单元格.      第二步:点击菜单中的“数据”->“数据有效性”->“数据 ...

  9. Html Table用JS导出excel格式问题 导出EXCEL后单元格里的000412341234会变成412341234 7-14 会变成 2018-7-14(7月14) 自定义格式 web利用table表格生成excel格式问题 js导出excel增加表头、mso-number-format定义数据格式 数字输出格式转换 mso-number-format:"\@"

    Html Table用JS导出excel格式问题 我在网上找的JS把HTML Tabel导出成EXCEL.但是如果Table里的数字内容为0开的的导成Excel后会自动删除0,我想以text的格式写入 ...

  10. poi读取合并单元格

    poi读取合并单元格 学习了:http://blog.csdn.net/ycb1689/article/details/9764191 进行了列合并单元格的修正:原来是我自己找错了地方: import ...

随机推荐

  1. 基于beautifulSoup进行电影网站排名的获取与格式化输出

    要求 编写代码完成以下任务: ① 将地址"http://www.cbooo.cn/year?year=2019"源代码使用任意方法保存到指定文件中(文件类型不限). ② 使用文件流 ...

  2. Go语言中的数据格式(json、xml 、msgpack、protobuf)

    在分布式的系统中,因为涉及到数据的传输,所以一定会进行数据的交换,此时就要定义数据交换的格式,例如二进制.Json.Xml等等.本篇文章就是总结一下常用的几种数据格式. 一.Json格式 如果想使用J ...

  3. leetcode刷题-1

    小A 和 小B 在玩猜数字.小B 每次从 1, 2, 3 中随机选择一个,小A 每次也从 1, 2, 3 中选择一个猜.他们一共进行三次这个游戏,请返回 小A 猜对了几次? 输入的guess数组为 小 ...

  4. Linux网络编程综合运用之MiniFtp实现(五)

    转眼兴奋的五一小长假就要到来了,在放假前夕还是需要保持一颗淡定的心,上次中已经对miniFTP有基础框架进行了搭建,这次继续进行往上加代码,这次主要还是将经历投射到handle_child()服务进程 ...

  5. SecureCRT中解决乱码的问题

    SecureCRT中文乱码的问题,解决方法如下: 打开Option菜单,点击Session Options-     在Appearance外观这里,选择编码--UTF-8     一定要记得先保存! ...

  6. xld特征

    halcon中什么是xld? xld(eXtended Line Descriptions) 扩展的线性描述,它不是基于像素的,人们称它是亚像素,只不过比像素更精确罢了,可以精确到像素内部的一种描述. ...

  7. C#经纬度加减运算(度°分′秒″格式)

    经度是分和秒是按60进位,如果要做运算第一步就是转换成浮点数,之后就是计算和还原. using System.Text.RegularExpressions; public static double ...

  8. TDOA Delayed Tx 实现以及验证

    在博文:https://www.cnblogs.com/tuzhuke/p/11638221.html 中描述了delayed tx实现方法,这里贴出全部delayed tx 代码以及对应验证代码 1 ...

  9. 四十五.加密与解密 AIDE入侵检测系统 扫描与抓包

    一.加密与解密 1.1 常见的加密算法 对称加密:怎么加密,就怎么解密 DES Date Encryption Standard AES Advance Encryption Standard 非对称 ...

  10. Planet.Earth.II.EP05.2016