您的位置:首页 > 其它

poi操作excel模板(excel2003,excel2007)

2014-06-06 13:13 239 查看
同上一篇文章

模版:



修改后:



代码:

package com.poi.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.poi.model.Person;

public class ExcelUtil {
private Workbook wb = null;
private String templatePath;
private int sheetIndex;
private List<String> keyList=new ArrayList<String>();
public ExcelUtil(String templatePath,int sheetIndex){
this.templatePath=templatePath;
this.sheetIndex=sheetIndex;
try {
InputStream inp = new FileInputStream(templatePath);
if (templatePath.endsWith("xlsx")) {
wb = new XSSFWorkbook(inp);
} else {
wb = new HSSFWorkbook(inp);
}
} catch (Exception e) {
e.printStackTrace();
}
getKeyList(sheetIndex);

}
private void getKeyList(int sheetIndex) {
int columnNum = 0;
Pattern pattern = Pattern.compile("%(.*?)%");
Sheet sheet = wb.getSheetAt(sheetIndex);
if (sheet.getRow(0) != null) {
columnNum = sheet.getRow(0).getLastCellNum()
- sheet.getRow(0).getFirstCellNum();
}
if (columnNum > 0) {
Row row = sheet.getRow(1);
for (int i = 0; i < columnNum; i++) {
Cell cell = row.getCell(i, Row.CREATE_NULL_AS_BLANK);
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
String str = cell.getStringCellValue().trim();
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
String key = matcher.group(1);
keyList.add(key);
}
break;
default:
break;
}
}
}
}
private List<String> getValue(Person person){
List<String> valueList=new ArrayList<String>();
for(String key:keyList){
String value=person.getString(key);
valueList.add(value);
}
return valueList;
}
public void createExcel(String newPath,List<Person> personList) {
String[] path=newPath.split(".xls");
if (templatePath.endsWith("xlsx")) {
newPath=path[0]+".xlsx";
}else{
newPath=path[0]+".xls";
}
Sheet sheet=wb.getSheetAt(sheetIndex);
try {
for(int i=0;i<personList.size();i++){
List<String> list=getValue(personList.get(i));
Row row=sheet.createRow(i+1);
for(int j=0;j<list.size();j++){
String str=list.get(j);
row.createCell(j).setCellValue(str);
}
}
FileOutputStream fos = new FileOutputStream(newPath);
wb.write(fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: