- 论坛徽章:
- 0
|
001 package com.diegoyun.tutorial;
002
003
004 import jxl.Workbook;
005 import jxl.Sheet;
006 import jxl.Cell;
007 import jxl.format.Alignment;
008 import jxl.format.VerticalAlignment;
009 import jxl.write.*;
010 import jxl.read.biff.BiffException;
011
012 import java.io.*;
013
014 /**
015 * User: Diegoyun
016 * Date: 2006-3-6
017 * Time: 22:05:09
018 */
019 public class JxlSample {
020 static String excelFilePath = "D:\\backup\\download\\sample.xls";
021
022 static void readXls() {
023 System.out.println("reading xls.");
024 Workbook book = null;
025 Sheet sheet = null;
026 try {
027 FileInputStream in = new FileInputStream(excelFilePath);
028
029
030 book = Workbook.getWorkbook(in);
031 sheet = book.getSheet(0); //get first sheet.
032
033 int cnt = sheet.getRows();
034 System.out.println(" row count is:" + cnt);
035
036 Cell cell = null;
037 for (int i = 0; i 038 //remember,the first parameter is column index ,and the second parameter is row index.
039 cell = sheet.getCell(0, i);
040 System.out.println(" cell value is:" + cell.getContents());
041 }
042 System.out.println("finished.");
043
044
045 } catch (FileNotFoundException e) {
046 e.printStackTrace();
047 } catch (IOException e) {
048 e.printStackTrace();
049 } catch (BiffException e) {
050 e.printStackTrace();
051 } finally {
052 if (sheet != null) {
053 sheet = null;
054 }
055 if (book != null) {
056 book = null;
057 }
058 }
059 }
060
061 static void writeXls() {
062 System.out.println("writing exls.");
063 WritableWorkbook wwb = null;
064 WritableSheet sheet = null;
065 try {
066 String xlsName = "D:\\backup\\download\\temp.xls";
067 File afile = new File(xlsName);
068 if (!afile.exists()) {
069 afile.createNewFile();
070 }
071 wwb = Workbook.createWorkbook(afile);
072 sheet = wwb.createSheet(xlsName, 0);
073
074 WritableFont wf = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false);
075 WritableCellFormat format = new WritableCellFormat(wf);
076 format.setAlignment(Alignment.CENTRE);
077 format.setVerticalAlignment(VerticalAlignment.CENTRE);
078 //remember,the first parameter is column index.
079 Label cell = new Label(0,0,"row 1,column 1",format);//set the value of cell (0,0)
080 sheet.addCell(cell);
081
082 cell = new Label(1,0,"row 1,column 2",format);
083 sheet.addCell(cell);
084
085 wwb.write();
086 System.out.println("finished.");
087
088 } catch (WriteException e) {
089 e.printStackTrace();
090 } catch (IOException e) {
091 e.printStackTrace();
092 } finally {
093 if (wwb != null) {
094 try {
095 wwb.close();
096 } catch (IOException e1) {
097 e1.printStackTrace();
098 }
099 }
100 }
101
102 }
103
104 public static void main(String[] args) {
105 readXls();
106 writeXls();
107 }
108 }
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/15511/showart_102237.html |
|