您的位置:首页 > 运维架构 > Apache

基于Apache POI 向xlsx写入数据

2015-08-29 14:30 691 查看

【0】写在前面

0.1) these codes are from 基于Apache POI 的向xlsx写入数据

0.2) this idea is from /article/3754914.html , adding some comments for easy understanding proves to be my work.

package com.cwind.poi;
import java.io.FileOutputStream;
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;

/**
* @author Billy Chen
*/
public class SimpleDatasheetWriter {

private static final String[] titles = {
"姓名", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};

//sample data to fill the sheet.
private static final String[][] data = {
{"AngelaBaby", "跑了", "跑了", "跑了", "跑了", "跑了"},
{"邓超", "跑了", "跑了", "没跑", "跑了", "跑了" },
{"王祖蓝", "没跑", "没跑", "没跑", "跑了", "跑了" },
{"王宝强", "跑了", "跑了", "跑了", "跑了", "跑了" },
{"郑恺", "跑了", "跑了", "跑了", "跑了", "跑了" }
};

public static void main(String[] args) throws Exception {

Workbook wb;


//创建工作簿

if(args.length > 0 && args[0].equals("-xls"))
wb = new HSSFWorkbook();
else
wb = new XSSFWorkbook();


//创建名为 Running Man 的纸张

Sheet sheet = wb.createSheet("Running Man");


//创建行坐标为0的行(为什么管它叫坐标,不把它叫做行,呵呵)

Row headerRow = sheet.createRow(0);


//设置行高

headerRow.setHeightInPoints(12.75f);

for (int i = 0; i < titles.length; i++) {


//创建行坐标为0的单元格,且其列坐标为i;

Cell cell = headerRow.createCell(i);


//设置单元格的value

cell.setCellValue(titles[i]);
}

Row row;
Cell cell;
int rownum = 1;
for (int i = 0; i < data.length; i++, rownum++) {


//创建行坐标为rownum 的行

row = sheet.createRow(rownum);
if(data[i] == null) continue;

for (int j = 0; j < data[i].length; j++) {


// 为行创建单元格;

cell = row.createCell(j);


// 设置单元格的value

cell.setCellValue(data[i][j]);
}
}

System.out.println("Default column width: " + sheet.getRow(0).getLastCellNum());
System.out.println("Default column width: " + sheet.getRow(0).getPhysicalNumberOfCells());


// Write the output to a file

String file = "E:/bench-cluster/temp-resource/RunningMan.xlsx";
if(wb instanceof XSSFWorkbook) file += "x";

FileOutputStream out = new FileOutputStream(file);
wb.write(out);
out.close();
//        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: