java 将.cvs传化成excel_Java导出Excel和CSV(简单Demo)

public classExportUtil {public static void main(String[] args) throwsFileNotFoundException, IOException{

List list = new ArrayList();

createData(list);

exportCSV(list,"/tmp/report.csv");

exportExcel(list,"/tmp/report.xls");

}public static void exportCSV(List list, String filePath) throwsIOException{

File file= newFile(filePath);if(file.exists())

file.delete();

CsvWriter wr= new CsvWriter(filePath, ',', Charset.forName("UTF-8"));

String[] contents= {"No", "date", "num", "percent"};

wr.writeRecord(contents);

ReportInfo info= newReportInfo();for(int i = 0; i < list.size(); i++){

info=list.get(i);

contents[0] =String.valueOf(info.getId());

contents[1] =info.getDate();

contents[2] =String.valueOf(info.getNum());

contents[3] = info.getPercent() + "%";

wr.writeRecord(contents);

}

wr.close();

}public static void exportExcel(List list, String filePath) throwsIOException{

File file= new File(filePath);//"/tmp/tmpfiles/workbook.xls"

if(file.exists())

file.delete();

FileOutputStream fileOut= new FileOutputStream(filePath);//创建excel表格//"/tmp/tmpfiles/workbook.xls"

Workbook wb = new HSSFWorkbook();//获取workbook//FileOutputStream fileOut = new FileOutputStream("workbook.xls");

HSSFSheet sheet = (HSSFSheet) wb.createSheet("report");//生成一个表格

sheet.setColumnWidth(1, 4000);

HSSFRow row= sheet.createRow((short)0);//创建行并插入表头

row.createCell(0).setCellValue("No");

row.createCell(1).setCellValue("date");

row.createCell(2).setCellValue("num");

row.createCell(3).setCellValue("percent");

ReportInfo info= newReportInfo();for(int i = 1; i <= list.size(); i++){//循环插入数据

info = list.get(i-1);

row=sheet.createRow(i);

row.createCell(0).setCellValue(info.getId());

row.createCell(1).setCellValue(info.getDate());

row.createCell(2).setCellValue(info.getNum());

row.createCell(3).setCellValue(info.getPercent()+"%");

}

wb.write(fileOut);

fileOut.close();

}public static void createData(Listlist){

ReportInfo tp= newReportInfo();

tp.setId(1);

tp.setNum(2);

tp.setPercent(50);

tp.setDate("2013-08-20");

list.add(tp);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值