1、环境搭建
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.0.1</version>
</dependency>
</dependencies>
2、API介绍
API名称
Workbook Excel的文档对象,针对不同的Excel类型分为:HSSFWorkbook(2003)和
XSSFWorkbool(2007)
Sheet Excel的表单
Row Excel的行
Cell Excel的格子单元
Font Excel字体
CellStyle 格子单元样式
3.1、创建EXcel
public class PoiTest01 {
//测试创建excel文件
public static void main(String[] args) throws Exception {
//1.创建workbook工作簿
Workbook wb = new XSSFWorkbook();
//2.创建表单Sheet
Sheet sheet = wb.createSheet("test");
//3.文件流
FileOutputStream fos = new FileOutputStream("E:\\test.xlsx");
//4.写入文件
wb.write(fos);
fos.close();
}
}
3.2、创建单元格
//测试创建单元格
public static void main(String[] args) throws Exception {
//1.创建workbook工作簿
Workbook wb = new XSSFWorkbook();
//2.创建表单Sheet
Sheet sheet = wb.createSheet("test");
//3.创建行对象,从0开始
Row row = sheet.createRow(3);
//4.创建单元格,从0开始
Cell cell = row.createCell(0);
//5.单元格写入数据
cell.setCellValue("传智播客");
//6.文件流
FileOutputStream fos = new FileOutputStream("E:\\test.xlsx");
//7.写入文件
wb.write(fos);
fos.close();
}
3.3、设置格式
//创建单元格样式对象
CellStyle cellStyle = wb.createCellStyle();
//设置边框
cellStyle.setBorderBottom(BorderStyle.DASH_DOT);//下边框
cellStyle.setBorderTop(BorderStyle.HAIR);//上边框
//设置字体
Font font = wb.createFont();//创建字体对象
font.setFontName("华文行楷");//设置字体
font.setFontHeightInPoints((short)28);//设置字号
cellStyle.setFont(font);
//设置宽高
sheet.setColumnWidth(0, 31 * 256);//设置第一列的宽度是31个字符宽度
row.setHeightInPoints(50);//设置行的高度是50个点
//设置居中显示
cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
//设置单元格样式
cell.setCellStyle(cellStyle);
//合并单元格
CellRangeAddress region =new CellRangeAddress(0, 3, 0, 2);
sheet.addMergedRegion(region);
3.4、绘制图形
//绘制图形
public static void main(String[] args) throws Exception {
//1.创建workbook工作簿
Workbook wb = new XSSFWorkbook();
//2.创建表单Sheet
Sheet sheet = wb.createSheet("test");
//读取图片流
FileInputStream stream=new FileInputStream("e:\\logo.jpg");
byte[] bytes= IOUtils.toByteArray(stream);
//读取图片到二进制数组
stream.read(bytes);
//向Excel添加一张图片,并返回该图片在Excel中的图片集合中的下标
int pictureIdx = wb.addPicture(bytes,Workbook.PICTURE_TYPE_JPEG);
//绘图工具类
CreationHelper helper = wb.getCreationHelper();
//创建一个绘图对象
Drawing<?> patriarch = sheet.createDrawingPatriarch();
//创建锚点,设置图片坐标
ClientAnchor anchor = helper.createClientAnchor();
anchor.setCol1(0);//从0开始
anchor.setRow1(0);//从0开始
//创建图片
Picture picture = patriarch.createPicture(anchor, pictureIdx);
picture.resize();
//6.文件流
FileOutputStream fos = new FileOutputStream("E:\\test.xlsx");
//7.写入文件
wb.write(fos);
fos.close();
}
3.5、加载Excel
public class PoiTest06 {
//单元格样式
public static void main(String[] args) throws Exception {
//1.创建workbook工作簿
Workbook wb = new XSSFWorkbook("E:\\demo.xlsx");
//2.获取sheet 从0开始
Sheet sheet = wb.getSheetAt(0);
int totalRowNum = sheet.getLastRowNum();
Row row = null;
Cell cell = null;
//循环所有行
for (int rowNum = 3; rowNum <sheet.getLastRowNum(); rowNum++) {
row = sheet.getRow(rowNum);
StringBuilder sb = new StringBuilder();
//循环每行中的所有单元格
for(int cellNum = 2; cellNum < row.getLastCellNum();cellNum++) {
cell = row.getCell(cellNum);
sb.append(getValue(cell)).append("-");
}
System.out.println(sb.toString());
}
}
//获取数据
private static Object getValue(Cell cell) {
Object value = null;
switch (cell.getCellType()) {
case STRING: //字符串类型
value = cell.getStringCellValue();
break;
case BOOLEAN: //boolean类型
value = cell.getBooleanCellValue();
break;
case NUMERIC: //数字类型(包含日期和普通数字)
if(DateUtil.isCellDateFormatted(cell)) {
value = cell.getDateCellValue();
}else{
value = cell.getNumericCellValue();
}
break;
case FORMULA: //公式类型
value = cell.getCellFormula();
break;
default:
break;
}
return value;
}
}
4、自定义工具类
4.1、自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ExcelAttribute {
/** 对应的列名称 */
String name() default "";
/** 列序号 */
int sort();
/** 字段类型对应的格式 */
String format() default "";
}
4.2、导出工具类
@Getter
@Setter
public class ExcelExportUtil<T> {
private int rowIndex;
private int styleIndex;
private String templatePath;
private Class clazz;
private Field fields[];
public ExcelExportUtil(Class clazz,int rowIndex,int styleIndex) {
this.clazz = clazz;
this.rowIndex = rowIndex;
this.styleIndex = styleIndex;
fields = clazz.getDeclaredFields();
}
/**
* 基于注解导出
*/
public void export(HttpServletResponse response,InputStream is, List<T> objs,String
fileName) throws Exception {
XSSFWorkbook workbook = new XSSFWorkbook(is);
Sheet sheet = workbook.getSheetAt(0);
CellStyle[] styles = getTemplateStyles(sheet.getRow(styleIndex));
AtomicInteger datasAi = new AtomicInteger(rowIndex);
for (T t : objs) {
Row row = sheet.createRow(datasAi.getAndIncrement());
for(int i=0;i<styles.length;i++) {
Cell cell = row.createCell(i);
cell.setCellStyle(styles[i]);
for (Field field : fields) {
if(field.isAnnotationPresent(ExcelAttribute.class)){
field.setAccessible(true);
ExcelAttribute ea = field.getAnnotation(ExcelAttribute.class);
if(i == ea.sort()) {
cell.setCellValue(field.get(t).toString());
}
}
}
}
}
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setContentType("application/octet-stream");
response.setHeader("content-disposition", "attachment;filename=" + new
String(fileName.getBytes("ISO8859-1")));
response.setHeader("filename", fileName);
workbook.write(response.getOutputStream());
}
public CellStyle[] getTemplateStyles(Row row) {
CellStyle [] styles = new CellStyle[row.getLastCellNum()];
for(int i=0;i<row.getLastCellNum();i++) {
styles[i] = row.getCell(i).getCellStyle();
}
return styles;
}
}
4.3、导入工具类
public class ExcelImportUtil<T> {
private Class clazz;
private Field fields[];
public ExcelImportUtil(Class clazz) {
this.clazz = clazz;
fields = clazz.getDeclaredFields();
}
/**
* 基于注解读取excel
*/
public List<T> readExcel(InputStream is, int rowIndex,int cellIndex) {
List<T> list = new ArrayList<T>();
T entity = null;
try {
XSSFWorkbook workbook = new XSSFWorkbook(is);
Sheet sheet = workbook.getSheetAt(0);
// 不准确
int rowLength = sheet.getLastRowNum();
System.out.println(sheet.getLastRowNum());
for (int rowNum = rowIndex; rowNum <= sheet.getLastRowNum(); rowNum++) {
Row row = sheet.getRow(rowNum);
entity = (T) clazz.newInstance();
System.out.println(row.getLastCellNum());
for (int j = cellIndex; j < row.getLastCellNum(); j++) {
Cell cell = row.getCell(j);
for (Field field : fields) {
if(field.isAnnotationPresent(ExcelAttribute.class)){
field.setAccessible(true);
ExcelAttribute ea =
field.getAnnotation(ExcelAttribute.class);
if(j == ea.sort()) {
field.set(entity, covertAttrType(field, cell));
}
}
}
}
list.add(entity);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* 类型转换 将cell 单元格格式转为 字段类型
*/
private Object covertAttrType(Field field, Cell cell) throws Exception {
String fieldType = field.getType().getSimpleName();
if ("String".equals(fieldType)) {
return getValue(cell);
}else if ("Date".equals(fieldType)) {
return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(getValue(cell)) ;
}else if ("int".equals(fieldType) || "Integer".equals(fieldType)) {
return Integer.parseInt(getValue(cell));
}else if ("double".equals(fieldType) || "Double".equals(fieldType)) {
return Double.parseDouble(getValue(cell));
}else {
return null;
}
}
/**
* 格式转为String
* @param cell
* @return
*/
public String getValue(Cell cell) {
if (cell == null) {
return "";
}
switch (cell.getCellType()) {
case STRING:
return cell.getRichStringCellValue().getString().trim();
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
Date dt = DateUtil.getJavaDate(cell.getNumericCellValue());
return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(dt);
} else {
// 防止数值变成科学计数法
String strCell = "";
Double num = cell.getNumericCellValue();
BigDecimal bd = new BigDecimal(num.toString());
if (bd != null) {
strCell = bd.toPlainString();
}
// 去除 浮点型 自动加的 .0
if (strCell.endsWith(".0")) {
strCell = strCell.substring(0, strCell.indexOf("."));
}
return strCell;
}
case BOOLEAN:
return String.valueOf(cell.getBooleanCellValue());
default:
return "";
}
}
}
5、工具类完成导入导出
5.1、导入数据
List<User> list = new ExcelImportUtil(User.class).readExcel(is, 1, 2);
5.2、导出数据
@RequestMapping(value = "/export/{month}", method = RequestMethod.GET)
public void export(@PathVariable(name = "month") String month) throws Exception {
//1.构造数据
List<EmployeeReportResult> list =
userCompanyPersonalService.findByReport(companyId,month+"%");
//2.加载模板流数据
Resource resource = new ClassPathResource("excel-template/hr-demo.xlsx");
FileInputStream fis = new FileInputStream(resource.getFile());
new ExcelExportUtil(EmployeeReportResult.class,2,2).
export(response,fis,list,"人事报表.xlsx");
}
标签:集成,sheet,wb,int,创建,POI,new,public,SpringBoot
From: https://www.cnblogs.com/moyanprogram/p/17006787.html