JAVA利用FreeMarker生成(导出)Excel表格

来源:互联网 发布:云烟淘宝客鹊桥助手 编辑:程序博客网 时间:2024/06/06 07:57
前言:根据前两遍博客可以很轻松的导出Word文档;今天就整理一下如何导出Excel表格;
 
 一、自定义Excel表格:如下图;
 
 二、另存为XML文件,如下图:
 
 三、修改参数值属性;
 在线格式化工具:http://tool.oschina.net/codeformat/xml/
 代码如下:1.xml(修改属性)
 <?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:o="urn:schemas-microsoft-com:office:office"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:html="http://www.w3.org/TR/REC-html40">
 <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
  <Created>2006-09-13T11:21:51Z</Created>
  <LastSaved>2017-05-08T09:14:58Z</LastSaved>
  <Version>12.00</Version>
 </DocumentProperties>
 <OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office">
  <RemovePersonalInformation/>
 </OfficeDocumentSettings>
 <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
  <WindowHeight>11640</WindowHeight>
  <WindowWidth>19200</WindowWidth>
  <WindowTopX>0</WindowTopX>
  <WindowTopY>90</WindowTopY>
  <ProtectStructure>False</ProtectStructure>
  <ProtectWindows>False</ProtectWindows>
 </ExcelWorkbook>
 <Styles>
  <Style ss:ID="Default" ss:Name="Normal">
   <Alignment ss:Vertical="Center"/>
   <Borders/>
   <Font ss:FontName="宋体" x:CharSet="134" ss:Size="11" ss:Color="#000000"/>
   <Interior/>
   <NumberFormat/>
   <Protection/>
  </Style>
 </Styles>
 <Worksheet ss:Name="Sheet1">
  <Table ss:ExpandedColumnCount="3" ss:ExpandedRowCount="20" x:FullColumns="1"
   x:FullRows="1" ss:DefaultColumnWidth="54" ss:DefaultRowHeight="13.5">
   <Row>
    <Cell><Data ss:Type="String">姓名</Data></Cell>
    <Cell><Data ss:Type="String">年龄</Data></Cell>
    <Cell><Data ss:Type="String">身高</Data></Cell>
   </Row>
   
   <#list list as test>
   <Row>
<Cell><Data ss:Type="String">${test.name}</Data></Cell>
<Cell><Data ss:Type="String">${test.age}</Data></Cell>
<Cell><Data ss:Type="String">${test.sg}</Data></Cell>
   </Row>
   </#list>
   
  </Table>
  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
   <PageSetup>
    <Header x:Margin="0.3"/>
    <Footer x:Margin="0.3"/>
    <PageMargins x:Bottom="0.75" x:Left="0.7" x:Right="0.7" x:Top="0.75"/>
   </PageSetup>
   <Print>
    <ValidPrinterInfo/>
    <PaperSizeIndex>9</PaperSizeIndex>
    <HorizontalResolution>200</HorizontalResolution>
    <VerticalResolution>200</VerticalResolution>
   </Print>
   <Selected/>
   <Panes>
    <Pane>
     <Number>3</Number>
     <ActiveRow>3</ActiveRow>
    </Pane>
   </Panes>
   <ProtectObjects>False</ProtectObjects>
   <ProtectScenarios>False</ProtectScenarios>
  </WorksheetOptions>
 </Worksheet>
</Workbook>
 注:row:代表一行,cell代表一个单元格;
 修改后把文件后缀名改成:.ftl格式文件;

 四、Java代码:如下:
package com.yls;


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;


public class TestExcel {
private Configuration configuration = null;


public TestExcel() {
configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8"); // 设置编码
}


public static void main(String[] args) {
TestExcel test = new TestExcel();
try {
test.createWord();
} catch (Exception e) {
e.printStackTrace();
}
}


public void createWord() {
Map<String, Object> dataMap = new HashMap<String, Object>();
getData(dataMap);
// configuration.setClassForTemplateLoading(this.getClass(), "/com");
// //FTL文件所存在的位置
try {
configuration.setDirectoryForTemplateLoading(new File("F:\\5\\"));
} catch (IOException e2) {
e2.printStackTrace();
} // 线上 :绝对路径
Template t = null;
try {
t = configuration.getTemplate("1.ftl", "UTF-8"); // 文件名,并且设置编码
} catch (IOException e) {
e.printStackTrace();
}
File outFile = new File("F:/5/outFilessa" + Math.random() * 10000 + ".xls"); // 生成文件的路径
Writer out = null;
try {
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8")); // 设置编码
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}


try {
t.process(dataMap, out);
out.flush();
out.close();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}


// 这里赋值的时候需要注意,xml中需要的数据你必须提供给它,不然会报找不到某元素错的.
private void getData(Map<String, Object> dataMap) {
// dataMap.put("name", "张三");
// dataMap.put("age", "22");
// dataMap.put("sg", "170cm");


List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
for (int i = 0; i < 10; i++) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "张三00" + i);
map.put("age", "1" + i);
map.put("sg", "17" + i);
list.add(map);
}
dataMap.put("list", list);


}
}
五、执行代码;
如何程序没报错的话,那么你的Excel表格已经成功生成出来了,但是,有时候会打不开?加载期间出现问题?如下图:

这是因为Excel在生成xml的时候,可能是为了不浪费资源吧,在生成时候,会指定Excel有多少行,如果超出了这个长度的话,它就会编译不通过.报错.


问题很好解决.
针对这2个问题,需要修改2个不同的地方.
1:工作表的到设置.就是Sheet了.ok,打开xml,搜索"Worksheet",如果你有多个工作表的话,找到你自己要的.

修改它的属性值"ss:ExpandedRowCount",看到这,应该懂了吧?把它设置大一点,或者通过程序传个值给它也可以.这个问题就解决了.

2:表,如果你有耐性,可以根据它给你的log去看看,一看也就知道了.不过不是很好找,呵呵.

搜索最后一个Row,修改它的属性值"ss:Index".

CE99B4C5.log日志内容如下:
在 工作表设置 出现 XML 错误
原因: 无效值
文件: F:\5\outFilessa398.4140447043494.xls
组: Worksheet
标志: Table
ATTRIB: ExpandedRowCount
值: 2

注意:ExpandedRowCount 这个值有点小,当前为2;改大一些就可以了;


六、导出Excel结果如下图:

 
 
 
 
 
 
原创粉丝点击