因公司项目需要,临时写的小程序。未优化,结构简单。
与上一版(https://my.oschina.net/u/3284390/blog/842084)相比的改进:
当待写出的数据为数字时,会自动转换单元格格式为数字(保留到小数点后两位);
修改方法为静态方法,使用时无需初始化ToExcel类;
具体用法见上一版说明。
package tools;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
/**
* 写出到Excel文件.
* @author AL
*
*/
public class ToExcel {
/**
* 匹配数字(非科学计数法).
*/
private static final Pattern general_num=Pattern.compile("^-{0,1}[0-9]+\\.{0,1}[0-9]*$");
/**
* 匹配数字(科学计数法).
*/
private static final Pattern notation_num=Pattern.compile("^-{0,1}[0-9]+\\.{0,1}[0-9]*E{1}-{0,1}[0-9]+$");
/**
* 逗号(英文输入状态).
*/
private static final String comma =",";
/**
* 等号(英文输入状态).
*/
private static final String equal_sign ="=";
/**
* 写出内容到Excel.
* map:key为Excel中每个分页的名称、List为分页的内容;
* fileName:最终输出的文件名,包含路径。
* @throws WriteExcelFailedException
*
*/
public static<T> void toExcel(Map<String,List<T>> map,String fileName) throws WriteExcelFailedException {
//新建文件输出流及Excel表格缓存区
FileOutputStream out=null;
HSSFWorkbook excel = null;
try {
out=new FileOutputStream(fileName+".xls");
excel = new HSSFWorkbook();
} catch (FileNotFoundException e) {
throw new WriteExcelFailedException("未知的异常",e);
}
//此对象用于设置单元格格式为数字格式并保留小数点后两位,备用
HSSFCellStyle cellStyle = excel.createCellStyle();
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
//若map为空,则重构一个map,装入一个空白键值对
if(map==null || map.isEmpty()){
map=new HashMap<>();
map.put("空", null);
}
//遍历键值对,将表格名称和表格内容传递给下一层,用于写出
for(Entry<String, List<T>> entry : map.entrySet()){
//向Excel(缓存区)内填充内容
writeWorkbook(entry.getValue(),entry.getKey(),excel,cellStyle);
}
//写出到磁盘文件
writeToDisk(out, excel);
}
/**
* 向Excel(缓存区)内填充内容.
* @param result
* @param sheetName
* @param excel
* @param cellStyle
*
*/
private static<T> void writeWorkbook(List<T> result, String sheetName, HSSFWorkbook excel, HSSFCellStyle cellStyle) {
if(sheetName==null || "".equals(sheetName)){//若sheetName为空,则填充“空”
sheetName="空";
}
HSSFSheet sheet = excel.createSheet(sheetName);
if (result == null || result.isEmpty()) {// 若集合为空,则写出“空”字符
sheet.createRow(0).createCell(0).setCellValue("空");
return;
}
//按照“,”将集合内元素toString的字符串切割成数组
String[] temp = result.get(0).toString().split(comma);
HSSFRow row = sheet.createRow(0);//获取此sheet表格的第一行
int times=temp.length;
for (int t = 0; t < times; t++) {//遍历数组,用于构造表头
row.createCell(t).setCellValue(temp[t].substring(0, temp[t].indexOf(equal_sign)));//只取“=”之前的字符
}
//遍历集合,填充表格内容
int size=result.size();
for (int i = 1; i <= size; i++) {
row = sheet.createRow(i);
String[] infos=result.get(i - 1).toString().split(comma);//将toString返回的字符串按","切割成数组
int round=infos.length;
for (int j = 0; j < round; j++) {
//只取“=”之后的字符
String info =infos[j].substring(infos[j].indexOf(equal_sign) + 1, infos[j].length()).trim();
//获取单元格
Cell cell=row.createCell(j);
//判断待输入的内容是否是数字
if (general_num.matcher(info).matches() || notation_num.matcher(info).matches()) {
cell.setCellStyle(cellStyle);
cell.setCellValue(Double.parseDouble(info));
}else{
cell.setCellValue(info);
}
}
}
}
/**
* 写出到磁盘文件.
* @param out
* @param excel
*
*/
private static void writeToDisk(FileOutputStream out, HSSFWorkbook excel) {
try {
excel.write(out);
if(out!=null){//关闭流
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 异常
* @author AL
*
*/
class WriteExcelFailedException extends Exception {
private static final long serialVersionUID = 1L;
public WriteExcelFailedException() {
super();
}
public WriteExcelFailedException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public WriteExcelFailedException(String message, Throwable cause) {
super(message, cause);
}
public WriteExcelFailedException(String message) {
super(message);
}
public WriteExcelFailedException(Throwable cause) {
super(cause);
}
}
© 著作权归作者所有