poi进行excle操作
一 excle导出:
所需要jar包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
代码:
package com.example.demo.controller; import javafx.scene.chart.XYChart;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException; import java.sql.ResultSet;
import java.sql.SQLException; /**
* Created by Administrator on 2019/2/19.
*/
public class PoiExcel {
public static void main(String[] args) throws SQLException {
String title[]= {"名字","课程","分数"};
//1.创建Excel工作簿
HSSFWorkbook workbook=new HSSFWorkbook();
//2.创建一个工作表
HSSFSheet sheet=workbook.createSheet("sheet2");
//3.创建第一行
HSSFRow row=sheet.createRow();
HSSFCell cell=null;
//4.插入第一行数据
for (int i = ; i < title.length; i++) {
cell=row.createCell(i);
cell.setCellValue(title[i]);
}
//5.追加数据
Data data=new Data();
ResultSet rs=data.getString();
while(rs.next()) {
HSSFRow row2=sheet.createRow(rs.getRow());
HSSFCell cell2=row2.createCell();
cell2.setCellValue(rs.getString());
cell2=row2.createCell();
cell2.setCellValue(rs.getString());
cell2=row2.createCell();
cell2.setCellValue(rs.getString());
}
//创建一个文件,将Excel内容存盘
File file=new File("e:/sheet2.xls");
try {
file.createNewFile();
FileOutputStream stream= FileUtils.openOutputStream(file);
workbook.write(stream);
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } }
二 读取:
//将Excel表中内容读取
public class PoiRead {
public static void main(String[] args) {
//需要解析的Excel文件
File file=new File("e:/sheet2.xls");
try {
//获取工作簿
FileInputStream fs=FileUtils.openInputStream(file);
HSSFWorkbook workbook=new HSSFWorkbook(fs);
//获取第一个工作表
HSSFSheet hs=workbook.getSheetAt();
//获取Sheet的第一个行号和最后一个行号
int last=hs.getLastRowNum();
int first=hs.getFirstRowNum();
//遍历获取单元格里的信息
for (int i = first; i <last; i++) {
HSSFRow row=hs.getRow(i);
int firstCellNum=row.getFirstCellNum();//获取所在行的第一个行号
int lastCellNum=row.getLastCellNum();//获取所在行的最后一个行号
for (int j = firstCellNum; j <lastCellNum; j++) {
HSSFCell cell=row.getCell(j);
String value=cell.getStringCellValue();
System.out.print(value+" ");
}
System.out.println();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
过高版本使用:
public class PoiExpExcel2 { /**
* POI生成Excel文件
* @author David
* @param args
*/
public static void main(String[] args) { String[] title = {"id","name","sex"}; //创建Excel工作簿
XSSFWorkbook workbook = new XSSFWorkbook();
//创建一个工作表sheet
Sheet sheet = workbook.createSheet();
//创建第一行
Row row = sheet.createRow();
Cell cell = null;
//插入第一行数据 id,name,sex
for (int i = ; i < title.length; i++) {
cell = row.createCell(i);
cell.setCellValue(title[i]);
}
//追加数据
for (int i = ; i <= ; i++) {
Row nextrow = sheet.createRow(i);
Cell cell2 = nextrow.createCell();
cell2.setCellValue("a" + i);
cell2 = nextrow.createCell();
cell2.setCellValue("user" + i);
cell2 = nextrow.createCell();
cell2.setCellValue("男");
}
//创建一个文件
File file = new File("e:/poi_test.xlsx");
try {
file.createNewFile();
//将Excel内容存盘
FileOutputStream stream = FileUtils.openOutputStream(file);
workbook.write(stream);
stream.close();
} catch (IOException e) {
e.printStackTrace();
} } }
3 定制版本导出:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jdom/jdom -->
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom</artifactId>
<version>1.1.</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<excel id="student" code="student" name="学生信息导入">
<colgroup>
<col index="A" width='17em'></col>
<col index="B" width='17em'></col>
<col index="C" width='17em'></col>
<col index="D" width='17em'></col>
<col index="E" width='17em'></col>
<col index="F" width='17em'></col>
</colgroup>
<title>
<tr height="16px">
<td rowspan="" colspan="" value="学生信息导入" />
</tr>
</title>
<thead>
<tr height="16px">
<th value="编号" />
<th value="姓名" />
<th value="年龄" />
<th value="性别" />
<th value="出生日期" />
<th value=" 爱好" />
</tr>
</thead>
<tbody>
<tr height="16px" firstrow="" firstcol="" repeat="">
<td type="string" isnullable="false" maxlength="" /><!--用户编号 -->
<td type="string" isnullable="false" maxlength="" /><!--姓名 -->
<td type="numeric" format="##0" isnullable="false" /><!--年龄 -->
<td type="enum" format="男,女" isnullable="true" /><!--性别 -->
<td type="date" isnullable="false" maxlength="" /><!--出生日期 -->
<td type="enum" format="足球,篮球,乒乓球" isnullable="true" /><!--爱好 -->
</tr>
</tbody>
</excel>
导出代码:
//准备工作:导入相关jar包commons-lang3-3.1.jar,jdom.jar,poi-3.11-20141221.jar
public class CreateTemp {
public static void main(String[] args) {
//获取解析Xml路径
String path=System.getProperty("user.dir")+"/student.xml";
File file=new File(path);
SAXBuilder builder=new SAXBuilder();
//解析xml文件
try {
Document document=builder.build(file);
//创建Excel
HSSFWorkbook workbook=new HSSFWorkbook();
//创建表格
HSSFSheet sheet=workbook.createSheet("sheet0");
//获取Xml文件的根节点
Element root=document.getRootElement();
//获取模板名称
String tempName=root.getAttributeValue("name");
//设置列宽
Element colgroup=root.getChild("colgroup");
setColumnWidth(sheet,colgroup);
//设置标题
int rownum = ;
int column = ;
Element title=root.getChild("title");
List<Element> trs=title.getChildren("tr");
for (int i = ; i <trs.size(); i++) {
Element tr=trs.get(i);
List<Element> tds=tr.getChildren("td");
HSSFRow row=sheet.createRow(rownum);
HSSFCellStyle cellStyle=workbook.createCellStyle();//创建单元格格式
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//标题居中
for (int j = ; j < tds.size(); j++) {
Element td=tds.get(j);
HSSFCell cell=row.createCell(j);
Attribute rowspan=td.getAttribute("rowspan");
Attribute colspan=td.getAttribute("colspan");
Attribute value=td.getAttribute("value");
if (value!=null) {
String content=value.getValue(); cell.setCellValue(content);
int rspan=rowspan.getIntValue()-;
int cspan=colspan.getIntValue()-;
//设置字体
HSSFFont font=workbook.createFont();
font.setFontName("仿宋_GB2312");
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//字体加粗
// font.setFontHeight((short)12);
font.setFontHeightInPoints((short));
cellStyle.setFont(font);
cell.setCellStyle(cellStyle);
//合并单元格居中
sheet.addMergedRegion(new CellRangeAddress(rspan, rspan, , cspan));
} }
rownum++; }
//设置表头
Element thead=root.getChild("thead");
trs=thead.getChildren("tr");
for (int i = ; i < trs.size(); i++) {
Element tr=trs.get(i);
HSSFRow row=sheet.createRow(rownum);
List<Element> ths=tr.getChildren("th");
for (int j = ; j <ths.size(); j++) {
Element th=ths.get(j);
HSSFCell cell=row.createCell(j);
Attribute value=th.getAttribute("value");
if (value!=null) {
String content=value.getValue();
cell.setCellValue(content); }
}
rownum++;
} //设置数据区域样式
Element tbody = root.getChild("tbody");
Element tr=tbody.getChild("tr");
int repeat=tr.getAttribute("repeat").getIntValue();
List<Element> tds=tr.getChildren("td");
for (int i = ; i < repeat; i++) {
HSSFRow row=sheet.createRow(rownum);
for (int j = ; j < tds.size(); j++) {
Element td=tds.get(j);
HSSFCell cell=row.createCell(j);
setType(workbook,cell,td);
}
}
rownum++;
//生成Excel导入模板
File tempFile=new File("e:/"+tempName+".xls");
tempFile.delete();
tempFile.createNewFile();
FileOutputStream fos=FileUtils.openOutputStream(tempFile);
workbook.write(fos);
fos.close(); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} private static void setType(HSSFWorkbook workbook, HSSFCell cell, Element td) {
Attribute typeAttr = td.getAttribute("type");
String type = typeAttr.getValue();
HSSFDataFormat format = workbook.createDataFormat();
HSSFCellStyle cellStyle = workbook.createCellStyle();
if("NUMERIC".equalsIgnoreCase(type)){
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
Attribute formatAttr = td.getAttribute("format");
String formatValue = formatAttr.getValue();
formatValue = StringUtils.isNotBlank(formatValue)? formatValue : "#,##0.00";
cellStyle.setDataFormat(format.getFormat(formatValue));
}else if("STRING".equalsIgnoreCase(type)){
cell.setCellValue("");
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cellStyle.setDataFormat(format.getFormat("@"));
}else if("DATE".equalsIgnoreCase(type)){
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
cellStyle.setDataFormat(format.getFormat("yyyy-m-d"));
}else if("ENUM".equalsIgnoreCase(type)){
CellRangeAddressList regions =
new CellRangeAddressList(cell.getRowIndex(), cell.getRowIndex(),
cell.getColumnIndex(), cell.getColumnIndex()); Attribute enumAttr = td.getAttribute("format");
String enumValue = enumAttr.getValue();
//加载下拉列表内容
DVConstraint constraint =
DVConstraint.createExplicitListConstraint(enumValue.split(","));
//数据有效性对象
HSSFDataValidation dataValidation = new HSSFDataValidation(regions, constraint);
workbook.getSheetAt().addValidationData(dataValidation);
}
cell.setCellStyle(cellStyle); } private static void setColumnWidth(HSSFSheet sheet, Element colgroup) {
List<Element> cols=colgroup.getChildren("col");//获取col的节点
for (int i = ; i < cols.size(); i++) {
Element col=cols.get(i);
Attribute width=col.getAttribute("width");//获取每列中的width属性
String unit = width.getValue().replaceAll("[0-9,\\.]", "");//单位
String value = width.getValue().replaceAll(unit, "");//数值
int v=;
if(StringUtils.isBlank(unit) || "px".endsWith(unit)){
v = Math.round(Float.parseFloat(value) * 37F);
}else if ("em".endsWith(unit)){
v = Math.round(Float.parseFloat(value) * 267.5F);
}//对单位进行判断
sheet.setColumnWidth(i, v);
} }
}
4 springmvc后台解析代码:
// excel导入
@RequestMapping("/export")
public void export(VivoIMEIUp zipRequest,
@RequestParam("file") MultipartFile file,
HttpServletRequest request, HttpServletResponse response) {
try {
// @RequestParam("file") MultipartFile file 是用来接收前端传递过来的文件
// 1.创建workbook对象,读取整个文档
InputStream inputStream = file.getInputStream();
POIFSFileSystem poifsFileSystem = new POIFSFileSystem(inputStream);
HSSFWorkbook wb = new HSSFWorkbook(poifsFileSystem);
// 2.读取页脚sheet
HSSFSheet sheetAt = wb.getSheetAt();
// 3.循环读取某一行
for (Row row : sheetAt) {
// 4.读取每一行的单元格
String stringCellValue = row.getCell().getStringCellValue(); // 第一列数据
String stringCellValue2 = row.getCell().getStringCellValue();// 第二列
// 写多少个具体看大家上传的文件有多少列.....
// 测试是否读取到数据,及数据的正确性
System.out.println(stringCellValue);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
}
poi进行excle操作的更多相关文章
- Poi读取Excle报错 java.util.zip.ZipException: invalid stored block lengths
一:Poi读取Excle报错 java.util.zip.ZipException: invalid stored block lengths 系统中需要导出excle签收单,excle模板是预设好 ...
- poi 导入Excle
一,AOP 是什么 Apache POI 提供java 程序对Microsoft Office格式文档的读写功能操作 二,所需要的jar包 三,实现代码 1, 读取Excle 返回Workbook格式 ...
- Poi导出Excle
场景 准备金系统需要从数据库读取大量数据存放到List集合中(可能还会做逻辑上的处理),并生成一个Excle文件,下载到客户本地. 问题一:客户体验 如果导出的文件比较大,比如几十万条数据,同步导出页 ...
- SpringMVC 实现POI读取Excle文件中数据导入数据库(上传)、导出数据库中数据到Excle文件中(下载)
读取Excale表返回一个集合: package com.shiliu.game.utils; import java.io.File; import java.io.FileInputStream; ...
- 使用POI进行Excel操作的总结一——创建Workbook,Sheet,Row以及Cell
前段时间,看在其他的网站上给出Excel文档的导入与导出操作,感觉很酷的样子,所以就学习了一下如何使用POI进行Excel的操作,现在对之前的学习过程进行一个总结. 一.现在普遍使用的Excel文档有 ...
- 在Struts2中使用poi进行excel操作下载的时候报getOutputStream() has already been called for this response 错误 [转]
在项目中用到了poi这个开源的操作excel文件的jar. 项目中用到struts2容器管理servlet.不是单纯的直接用servlet. workbook.write(os); ...
- POI中excle样式怎么写
POI中可能会用到一些需要设置EXCEL单元格格式的操作小结: 先获取工作薄对象: HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb ...
- 利用poi向excle写入数据
import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import org ...
- POI设置excle单元格样式
Java利用POI生成Excel强制换行 使用POI创建一个简单的 myXls.xls 文件 常用的包为 org.apache.poi.hssf.usermodel.*; ...
随机推荐
- UML设计九种图例
一.作为一种建模语言,UML的定义包括UML语义和UML表示法两个部分. UML语义:描述基于UML的精确元模型定义. UML表示法:定义UML符号的表示法,为开发者或开发工具使用这些图形符号和文本语 ...
- CALayer绘图
一.CALayer绘图方式 Layer绘图有两种方法,不管使用哪种方法绘制完必须调用图层的setNeedDisplay方法(注意是图层的方法,不是UIView的方法,UIView的setNeedDis ...
- css样式文件命名规范
样式文件命名规范 主要 master.css, style.css, main.css 布局 layout.css 专栏 columns.css 文字 font.css 打印 print.css 主题 ...
- HDU 4348(主席树 标记永久化)
题面一看就是裸的数据结构题,而且一看就知道是主席树... 一共四种操作:1:把区间[l, r]的数都加上d,并且更新时间.2:查询当前时间的区间和.3:查询历史时间的区间和.4:时光倒流到某个时间. ...
- Cocos2d-x 网络编程
主要介绍内容:Http协议,Socket协议,webSocket协议, Cocos2d-x中的相关类和方法 1 Http协议 HTTP协议也叫超文本传输协议.是互联网广泛使用的通信协议,常用于B/S架 ...
- linux鸟哥的私房菜
这书还是感觉非常棒,真的是授之以渔而不是授之以鱼.我觉得只需要掌握一个命令就可以了man -k KEYWORD 比如我想查找和防火墙相关的命令,那么 man -k firewall 结果是ufw 然后 ...
- php学习笔记-if else
生活不会总是波澜不惊的,要是那样也没有什么意思.代码也一样,if else的出现为平静的生活带来一点变化. <?php $money = 1000; if($money>0) { //sl ...
- LeetCode第70题:爬楼梯
问题描述 假设你正在爬楼梯.需要 n 阶你才能到达楼顶. 每次你可以爬 1 或 2 个台阶.你有多少种不同的方法可以爬到楼顶呢? 注意:给定 n 是一个正整数. 示例 1: 输入: 2 输出: 2 解 ...
- c#中public,private,protected,internal的区别
public 可以被外部成员调用 private 只能在被类的成员调用 protected 只能在被类的成员和该类的子类调用 internal 可以在当前项目调用 pub ...
- <超越死亡:恩宠与勇气>节选
我有一副身体,但我并非自己的身体.我可以看见并感觉到我的身体,然而凡是可以被看见以及被感觉到的,并不是真正的观者.我的身体也许疲惫或兴奋,生病或健康,沉重或轻松,也可能焦虑或平静,但这与内在的真我全然 ...