JAva excelを作成する2つの方法
3377 ワード
方法1、サードパーティjarパッケージを利用する:jxl.jar
また、Excelの内容は次のとおりです.
方法二、jarパッケージを利用する:poi-3.2-FINAL-20081019.jar
ここに関連するjarパッケージを追加します:jxl.jar,poi.jar のダウンロードアドレス:
http://download.csdn.net/download/kuangfengbuyi/4658127
public void createExcel(){
try{
//
WritableWorkbook workbook = Workbook.createWorkbook(new File("test.xls"));
// “ ” , 0
WritableSheet sheet = workbook.createSheet(" ", 0);
// Label (0,0)
// test
Label label = new Label(0,0,"test");
//
sheet.addCell(label);
/*
* Number ,
* , , 789.123*/
jxl.write.Number number = new jxl.write.Number(1,0,756);
sheet.addCell(number);
sheet.insertColumn(1);
workbook.copySheet(0, " ", 1);
WritableSheet sheet2 = workbook.getSheet(1);
Range range = sheet2.mergeCells(0, 0, 0, 8);
sheet2.unmergeCells(range);
sheet2.addImage(new WritableImage(5, 5, 10, 20, new File("F:\\09.png")));
CellView cv = new CellView();
WritableCellFormat cf = new WritableCellFormat();
cf.setBackground(Colour.BLUE);
cv.setFormat(cf);
cv.setSize(6000);
cv.setDimension(10);
sheet2.setColumnView(2, cv);
workbook.write();
workbook.close();
}catch(Exception e){}
}
また、Excelの内容は次のとおりです.
public void displayExcel(){
try {
Workbook wb = Workbook.getWorkbook(new File("test.xls"));
Sheet s = wb.getSheet(0);
System.out.println(s.getCell(0, 0).getContents());
} catch (BiffException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
方法二、jarパッケージを利用する:poi-3.2-FINAL-20081019.jar
public void exportExcel(){
HSSFWorkbook wb = new HSSFWorkbook();//
HSSFFont font = wb.createFont();
font.setFontHeightInPoints((short)24);
font.setFontName(" ");
font.setColor(HSSFColor.BLACK.index);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THICK);
style.setFont(font);
HSSFSheet sheet = wb.createSheet("test");// , test
int iRow = 0;//
int iMaxCol = 17;//
HSSFRow row = sheet.createRow(iRow);
HSSFCell cell = row.createCell((short)0);
cell.setCellValue(new HSSFRichTextString(" excel"));
cell.setCellStyle(style);
sheet.addMergedRegion(new Region(iRow,(short)0,iRow,(short)(iMaxCol-1)));
ByteArrayOutputStream os = new ByteArrayOutputStream();
try{
wb.write(os);
}catch(IOException e){
e.printStackTrace();
//return null;
}
byte[] xls = os.toByteArray();
File file = new File("test01.xls");
OutputStream out = null;
try {
out = new FileOutputStream(file);
try {
out.write(xls);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
ここに関連するjarパッケージを追加します:jxl.jar,poi.jar のダウンロードアドレス:
http://download.csdn.net/download/kuangfengbuyi/4658127