一、概述

  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. {RuntimeError} An attempt has been made to start a new process before the current process has finished its bootstrapping phase.This probably means that you are not using fork to start your child...

    加载数据时出现报错: RuntimeError:         An attempt has been made to start a new process before the        c ...

  2. Java学习笔记——第3篇

    面向对象 结构化程序的任何一个结构都具有唯一的入口和唯一的出口,并且程序不会出现死循环. 虽然Java是面向对象的,但Java的方法里则是一种结构化的程序流. 面向对象的基本思想:类.对象.继承.封装 ...

  3. 运输层3——传输控制协议TCP概述

    目录 1. TCP最主要的特点 2. TCP的连接 3. socket在不同场景中的含义 写在前面:本文章是针对<计算机网络第七版>的学习笔记 运输层1--运输层协议概述 运输层2--用户 ...

  4. 【原创】改进的大马webshell,过市面上任何防护

    因为之前使用的webshell大马很多都没用了,都被安全防护拦截了,所以通过几个大牛的指点和网上的教程整理而成自己做的增强版的webshell大马,我这个是源码,部分无加密! <?php $pa ...

  5. vmware 共享文件夹不显示文件的问题

    上海SEO:安装vmtools后还是不显示执行以下操作//但是只有root权限才行 1:输入命令  sudo apt install open-vm-tools 安装工具2:输入命令 sudo vmh ...

  6. nginx配置url伪静态

    rewrite 规则 定向路径 重写类型; 举例: rewrite  (.*)/web/(.*)-(.*)-(.*).html$  $1/web/index.php?r=$2/$3/$4  last; ...

  7. linux文件共享服务

    linux文件共享配置 Windows访问linux 以下操作都在关闭防火墙和关闭selinux的环境下. 关闭防火墙的命令:service iptables stop关闭SELINUX命令:sete ...

  8. HR#7 题解

    T1 签到题 #include<bits/stdc++.h> #define R register int using namespace std; inline int g() { R ...

  9. The backup set holds a backup of a database other than the existing ‘dbName’ database

     [Solved] System.Data.SqlClient.SqlError: The backup set holds a backup of a database other than t ...

  10. tarjan模板完整版

    https://www.luogu.org/problem/P2863 #include<cstdio> #include<vector> using namespace st ...