java如何导出et文件_Springboot使用POI实现导出Excel文件示例

前面讲述了使用POI导出Word文件和读取Excel文件,这两个例子都相对简单,接下来要讲述的使用POI导出Excel文件要复杂得多,内容也会比较长。

创建表头信息

表头信息用于自动生成表头结构及排序

public class ExcelHeader implements Comparable{

/**

* excel的标题名称

*/

private String title;

/**

* 每一个标题的顺序

*/

private int order;

/**

* 说对应方法名称

*/

private String methodName;

public String getTitle() {

return title;

}

public void setTitle(String title) {

this.title = title;

}

public int getOrder() {

return order;

}

public void setOrder(int order) {

this.order = order;

}

public String getMethodName() {

return methodName;

}

public void setMethodName(String methodName) {

this.methodName = methodName;

}

public int compareTo(ExcelHeader o) {

return order>o.order?1:(order

}

public ExcelHeader(String title, int order, String methodName) {

super();

this.title = title;

this.order = order;

this.methodName = methodName;

}

}

表头信息的Annotation

/**

* 用来在对象的get方法上加入的annotation,通过该annotation说明某个属性所对应的标题

* Created by 钟述林 on 2016/10/29 0:14.

*/

@Retention(RetentionPolicy.RUNTIME)

public @interface ExcelResources {

/**

* 属性的标题名称

* @return

*/

String title();

/**

* 在excel的顺序

* @return

*/

int order() default 9999;

}

创建数据实体

public class WebDto {

//网站名称

private String name;

//网址

private String url;

//用户名

private String username;

//密码

private String password;

//日均访问量

private Integer readCount;

public WebDto(String name, String url, String username, String password, Integer readCount) {

this.name = name;

this.url = url;

this.username = username;

this.password = password;

this.readCount = readCount;

}

public WebDto() {}

@Override

public String toString() {

return "WebDto{" +

"name='" + name + '\'' +

", url='" + url + '\'' +

", username='" + username + '\'' +

", password='" + password + '\'' +

", readCount=" + readCount +

'}';

}

@ExcelResources(title="网站名称",order=1)

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

@ExcelResources(title="网址",order=2)

public String getUrl() {

return url;

}

public void setUrl(String url) {

this.url = url;

}

@ExcelResources(title="用户名",order=3)

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

@ExcelResources(title="密码",order=4)

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

@ExcelResources(title="日均访问量",order=5)

public Integer getReadCount() {

return readCount;

}

public void setReadCount(Integer readCount) {

this.readCount = readCount;

}

}

注意:这里使用到了@ExcelResources来自动识别表头信息及序号

获取模板文件的工具类

public class TemplateFileUtil {

public static FileInputStream getTemplates(String tempName) throws FileNotFoundException {

return new FileInputStream(ResourceUtils.getFile("classpath:excel-templates/"+tempName));

}

}

注意:从这里可以看出,所有的Excel模板文件都放在resources/excel-templates/目录下。

模板工具类

通过此类可以自动复制表样式等功能

/**

* 该类实现了基于模板的导出

* 如果要导出序号,需要在excel中定义一个标识为sernums

* 如果要替换信息,需要传入一个Map,这个map中存储着要替换信息的值,在excel中通过#来开头

* 要从哪一行那一列开始替换需要定义一个标识为datas

* 如果要设定相应的样式,可以在该行使用styles完成设定,此时所有此行都使用该样式

* 如果使用defaultStyls作为表示,表示默认样式,如果没有defaultStyles使用datas行作为默认样式

* Created by 钟述林 393156105@qq.com on 2016/10/28 23:38.

*/

public class ExcelTemplate {

/**

* 数据行标识

*/

public final static String DATA_LINE = "datas";

/**

* 默认样式标识

*/

public final static String DEFAULT_STYLE = "defaultStyles";

/**

* 行样式标识

*/

public final static String STYLE = "styles";

/**

* 插入序号样式标识

*/

public final static String SER_NUM = "sernums";

private static ExcelTemplate et = new ExcelTemplate();

private Workbook wb;

private Sheet sheet;

/**

<
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java使用POI库可以实现Excel文件的操作,包括读取、写入、修改等。下面是使用POI实现带图片的模板导出Excel示例代码: 1. 导入依赖库 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.17</version> </dependency> ``` 2. 创建Excel模板 创建一个Excel模板,包含需要导出的数据和图片。示例模板如下: ![excel_template.png](https://cdn.jsdelivr.net/gh/occlive/ImageHost01/excel_template.png) 3. 编写Java代码 Excel模板创建完成后,就可以使用POI库来读取模板、填充数据和图片、导出Excel文件了。以下是示例代码: ```java import java.io.*; import java.util.*; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.*; public class ExcelExportUtil { public static void export(List<Map<String, Object>> dataList, String templatePath, String exportPath) throws Exception { InputStream is = new FileInputStream(templatePath); XSSFWorkbook workbook = new XSSFWorkbook(is); XSSFSheet sheet = workbook.getSheetAt(0); int rowIndex = 1; for (Map<String, Object> data : dataList) { XSSFRow row = sheet.createRow(rowIndex++); int cellIndex = 0; for (String key : data.keySet()) { Object value = data.get(key); XSSFCell cell = row.createCell(cellIndex++); if (value instanceof String) { cell.setCellValue((String) value); } else if (value instanceof Double) { cell.setCellValue((Double) value); } else if (value instanceof Date) { cell.setCellValue((Date) value); } else if (value instanceof Calendar) { cell.setCellValue((Calendar) value); } else if (value instanceof Boolean) { cell.setCellValue((Boolean) value); } else if (value instanceof byte[]) { // 插入图片 int pictureIdx = workbook.addPicture((byte[]) value, Workbook.PICTURE_TYPE_JPEG); CreationHelper helper = workbook.getCreationHelper(); Drawing drawing = sheet.createDrawingPatriarch(); ClientAnchor anchor = helper.createClientAnchor(); anchor.setCol1(cellIndex - 1); anchor.setRow1(rowIndex - 1); Picture pict = drawing.createPicture(anchor, pictureIdx); pict.resize(); } else { cell.setCellValue(value.toString()); } } } OutputStream os = new FileOutputStream(exportPath); workbook.write(os); os.close(); } } ``` 代码解释: - `export`方法接受一个数据列表、一个Excel模板文件路径和一个导出Excel文件路径作为参数,将数据填充到模板中并导出Excel文件 - 首先使用`FileInputStream`读取Excel模板文件,然后创建`XSSFWorkbook`和`XSSFSheet`对象 - 遍历数据列表,对于每个数据项,创建一个新的行,并为每个属性创建一个单元格,使用单元格的`setCellValue`方法填充数据 - 如果属性的值是一个图片,则调用`Workbook.addPicture`方法将图片添加到工作簿中,并使用`Sheet.createDrawingPatriarch`方法创建绘图对象,在单元格上创建图片,最后调用`Picture.resize`方法调整图片大小 - 最后使用`FileOutputStream`将工作簿写入Excel文件中 4. 调用导出方法 在main方法中调用export方法进行导出: ```java import java.util.*; public class Main { public static void main(String[] args) throws Exception { List<Map<String, Object>> dataList = new ArrayList<>(); Map<String, Object> data1 = new HashMap<>(); data1.put("name", "张三"); data1.put("age", 20); data1.put("avatar", FileUtils.readFileToByteArray(new File("avatar.jpg"))); dataList.add(data1); Map<String, Object> data2 = new HashMap<>(); data2.put("name", "李四"); data2.put("age", 25); data2.put("avatar", FileUtils.readFileToByteArray(new File("avatar.jpg"))); dataList.add(data2); ExcelExportUtil.export(dataList, "template.xlsx", "export.xlsx"); } } ``` 以上代码会生成一个包含两条记录和图片的Excel文件,效果如下: ![excel_export.png](https://cdn.jsdelivr.net/gh/occlive/ImageHost01/excel_export.png) 希望对您有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值