最近業務需要做復雜的Excel導出功能,由於Execl樣式復雜,本來想做基於標簽占位符的導出,由於時間有限,沒有時間預言和寫demo,最后還是選擇了基於POI的導出,就是樣式復雜了點。
現在有時間研究了一下使用freemarker導出復雜的excel表格(word也是可以的)。
一、首先根據最終需要導出的excel表格的格式,用假數據填充后生成一個excel模板。
例如下面使我們要導出的人員信息。
二、Execl另存為.xml文件
如果報以下錯誤
請選擇
三、通過Freemarker進行xml文件編輯
四、Java代碼開發
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.29</version>
</dependency>
實體類:
public class UserInfo {
private String username;
private Integer age;
private String phone;
private String sex;
private String address;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
核心代碼
public static void main(String[] args) throws IOException, TemplateException {
Configuration config = new Configuration(Configuration.VERSION_2_3_0);
//模板所在文件夾
config.setDirectoryForTemplateLoading(new File("D:/execltest"));
config.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_0));
//模板名稱
Template template = config.getTemplate("name2.xml");
FileOutputStream fileOutputStream = new FileOutputStream("D:/execltest/name.xls");
OutputStreamWriter out = new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8);
List<UserInfo> list = Lists.newArrayListWithCapacity(5);
for (int i = 0; i < 5; i++) {
UserInfo userInfo = new UserInfo();
userInfo.setUsername("張三" + i);
userInfo.setAge(22 + i);
userInfo.setPhone("15094037899");
userInfo.setSex("男");
userInfo.setAddress("北京");
list.add(userInfo);
}
Map<String, Object> map = Maps.newHashMap();
map.put("personList",list);
template.process(map,out);
}
五.效果
遇到的問題:
我是用wps生成的xml,最后生成的excel,在office excel打開,報如下錯誤,但是用wps打開是沒問題的,可能是兼容性問題:
但是點擊也是能打開的。這個問題用office excel生成xml進行驗證,還是報上面的錯誤,網上的方法都試了沒用。
打開excel文件,會出現上面的彈框,這個問題一直不好解決,因為我們生成的是xml標記語言,只是將后綴改為xls顯示而已,但實際上不是xls文件,如果有好的解決方案(不是修改注冊表的掩耳盜鈴的方式),期待留言!
導出word也是提示上面錯誤
六:建議
excel右鍵導出xml(最好利用excel microsoft導出,不要用wps導出xml,因為microsoft導出的xml格式簡單)
ss:ExpandedRowCount="3" wps可以不改,microsoft設置越大越好(例如999999),或者用freemarker來傳值,不能小於實際行數
excel(最好導出的格式都是.xls,不要生成.xlsx,踩過坑的都知道,由xml生成的xlsx microsoft打不開)
word(最好導出的格式是.doc,不要生成.docx)
參考來自: https://blog.csdn.net/m0_38106299/article/details/80830161
微信公眾號