您的位置:首页 > 其它

导出Excel

2016-04-15 09:55 274 查看
package com.excel.export;

import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
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.xssf.usermodel.XSSFWorkbook;

public class ExportExcel2 {

public static void main(String[] args) throws Exception {
List<String> title = new ArrayList<String>();
title.add("id");
title.add("name");
title.add("sex");
List<List<String>> contents = new ArrayList<List<String>>();
for(int i=1;i<11;i++){
List<String> list = new ArrayList<String>();
list.add(i+"");
list.add("James_"+i);
list.add("man");
contents.add(list);
}

if (title == null) {
throw new Exception("导出表头不能为空");
}
if (contents != null && contents.get(0).size() != title.size()) {
throw new Exception("表头和行数据不对称");
}

//创建Excel工作簿
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet();
Row row = sheet.createRow(0);
Cell cell = null;
//插入第一行数据 id,name,sex
for(int i=0;i<title.size();i++){
cell = row.createCell(i);
cell.setCellValue(title.get(i));
}
//追加数据

for(int i=1;i<=contents.size();i++){
Row nextRow = sheet.createRow(i);
for(int j=0;j<contents.get(i-1).size();j++){
Cell cell2 = nextRow.createCell(j);
cell2.setCellValue(contents.get(i-1).get(j));
}
}
//创建一个文件
File file = new File("e:/content.xlsx");
try {
file.createNewFile();
FileOutputStream fop = FileUtils.openOutputStream(file);
workbook.write(fop);
fop.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("------done----");

}

}

http://blog.csdn.net/ptzrbin/article/details/8751293
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: