XSS Excel

package com.pengtao.www;

import java.awt.Color;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelWriter {

/**
* Write Excel 2007
*/
public void buildXSLXExcel(List<String> list, String filePath) {
XSSFWorkbook workBook = null;
String[] cellTitle = { "Object Name","XPath"};
try {
workBook = new XSSFWorkbook();// Create workbook
XSSFSheet sheet = workBook.createSheet();//create work sheet
workBook.setSheetName(0, "Repository");// set sheet name
XSSFRow titleRow = sheet.createRow(0);// Create first row

XSSFCell ObjectCell = titleRow.createCell(0, 0);
XSSFCell XpathCell = titleRow.createCell(2, 0);

//Create color style
XSSFCellStyle cellStyle=workBook.createCellStyle();
cellStyle.setFillForegroundColor(new XSSFColor(new Color(100, 100, 100)));
cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);

//Create font style
Font titleFont = workBook.createFont(); 
titleFont.setFontHeightInPoints((short) 12); 
titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);

cellStyle.setFont(titleFont);


//Add color style
ObjectCell.setCellStyle(cellStyle);
XpathCell.setCellStyle(cellStyle);

//Add font style


//Set value
ObjectCell.setCellValue(cellTitle[0]);
XpathCell.setCellValue(cellTitle[1]);


if (list != null && !list.isEmpty()) {
for (int i = 0; i < list.size(); i=i+2) {
XSSFRow row = sheet.createRow(i+1);
XSSFCell Objectcell = row.createCell(0);
XSSFCell XPathcell = row.createCell(2);
Objectcell.setCellValue(list.get(i));
XPathcell.setCellValue(list.get(i+1));

}
}

File file = new File(filePath);
File parent = file.getParentFile();
if(!parent.exists()) {
parent.mkdir();
}
if(!file.exists()){
file.createNewFile();
}
FileOutputStream outStream = new FileOutputStream(file);
workBook.write(outStream);
outStream.flush();
outStream.close();

} catch (Exception e) {
System.err.println(e);
e.printStackTrace();
}
}

public static void main(String[] args) {
// TODO Auto-generated method stub
List<String> list = new ArrayList<String>();
list.add("test1");
list.add("test2");
list.add("test3");
list.add("test4");
ExcelWriter w = new ExcelWriter();
w.buildXSLXExcel(list, "./output/test.xlsx");
}

}

类图

猜你喜欢

转载自201505240204.iteye.com/blog/2264569
xss