jxl使用小结

最近需要将MongoDB里面的数据导入到Excel,使用到了jxl.jar,总结一下下~

java 操作 Excel 最常用的就是JXL(java excel api)和POI,今先看下JXL吧。首先可以到http://www.andykhan.com/jexcelapi/download.html 下载最新的jxl.jar,里面有它的jar包和API,内有一个小例子,可以参考一下。

JXL 用起来挺简单的,不过相应的其功能也并不是十分强大,对于一般的简单的excel操作还可以,对于太复杂的还是有些吃力,另外需要说明的是,这套API对图形和图表的支持很有限,而且仅仅识别PNG格式。

1. Create an Excel Spreadsheet

Create a new Java project called de.vogella.java.excel. Create the de.vogella.java.excel.writer package and the following class.

<span style="font-size:14px;">package writer;

import java.io.File;
import java.io.IOException;
import java.util.Locale;

import jxl.CellView;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.UnderlineStyle;
import jxl.write.Formula;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;


public class WriteExcel {

  private WritableCellFormat timesBoldUnderline;
  private WritableCellFormat times;
  private String inputFile;
  
public void setOutputFile(String inputFile) {
  this.inputFile = inputFile;
  }

  public void write() throws IOException, WriteException {
    File file = new File(inputFile);
    WorkbookSettings wbSettings = new WorkbookSettings();

    wbSettings.setLocale(new Locale("en", "EN"));

    WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings);
    workbook.createSheet("Report", 0);
    WritableSheet excelSheet = workbook.getSheet(0);
    createLabel(excelSheet);
    createContent(excelSheet);

    workbook.write();
    workbook.close();
  }

  private void createLabel(WritableSheet sheet)
      throws WriteException {
    // Lets create a times font
    WritableFont times10pt = new WritableFont(WritableFont.TIMES, 10);
    // Define the cell format
    times = new WritableCellFormat(times10pt);
    // Lets automatically wrap the cells
    times.setWrap(true);

    // create create a bold font with unterlines
    WritableFont times10ptBoldUnderline = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false,
        UnderlineStyle.SINGLE);
    timesBoldUnderline = new WritableCellFormat(times10ptBoldUnderline);
    // Lets automatically wrap the cells
    timesBoldUnderline.setWrap(true);

    CellView cv = new CellView();
    cv.setFormat(times);
    cv.setFormat(timesBoldUnderline);
    cv.setAutosize(true);

    // Write a few headers
    addCaption(sheet, 0, 0, "Header 1");
    addCaption(sheet, 1, 0, "This is another header");
    

  }

  private void createContent(WritableSheet sheet) throws WriteException,
      RowsExceededException {
    // Write a few number
    for (int i = 1; i < 10; i++) {
      // First column
      addNumber(sheet, 0, i, i + 10);
      // Second column
      addNumber(sheet, 1, i, i * i);
    }
    // Lets calculate the sum of it
    StringBuffer buf = new StringBuffer();
    buf.append("SUM(A2:A10)");
    Formula f = new Formula(0, 10, buf.toString());
    sheet.addCell(f);
    buf = new StringBuffer();
    buf.append("SUM(B2:B10)");
    f = new Formula(1, 10, buf.toString());
    sheet.addCell(f);

    // now a bit of text
    for (int i = 12; i < 20; i++) {
      // First column
      addLabel(sheet, 0, i, "Boring text " + i);
      // Second column
      addLabel(sheet, 1, i, "Another text");
    }
  }

  private void addCaption(WritableSheet sheet, int column, int row, String s)
      throws RowsExceededException, WriteException {
    Label label;
    label = new Label(column, row, s, timesBoldUnderline);
    sheet.addCell(label);
  }

  private void addNumber(WritableSheet sheet, int column, int row,
      Integer integer) throws WriteException, RowsExceededException {
    Number number;
    number = new Number(column, row, integer, times);
    sheet.addCell(number);
  }

  private void addLabel(WritableSheet sheet, int column, int row, String s)
      throws WriteException, RowsExceededException {
    Label label;
    label = new Label(column, row, s, times);
    sheet.addCell(label);
  }

  public static void main(String[] args) throws WriteException, IOException {
    WriteExcel test = new WriteExcel();
    test.setOutputFile("c:/temp/lars.xls");
    test.write();
    System.out
        .println("Please check the result file under c:/temp/lars.xls ");
  }
} </span>

2.Read an existing Excel Spreadsheet

<span style="font-size:14px;">package reader;

import java.io.File;
import java.io.IOException;

import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class ReadExcel {

  private String inputFile;

  public void setInputFile(String inputFile) {
    this.inputFile = inputFile;
  }

  public void read() throws IOException  {
    File inputWorkbook = new File(inputFile);
    Workbook w;
    try {
      w = Workbook.getWorkbook(inputWorkbook);
      // Get the first sheet
      Sheet sheet = w.getSheet(0);
      // Loop over first 10 column and lines

      for (int j = 0; j < sheet.getColumns(); j++) {
        for (int i = 0; i < sheet.getRows(); i++) {
          Cell cell = sheet.getCell(j, i);
          CellType type = cell.getType();
          if (type == CellType.LABEL) {
            System.out.println("I got a label "
                + cell.getContents());
          }

          if (type == CellType.NUMBER) {
            System.out.println("I got a number "
                + cell.getContents());
          }

        }
      }
    } catch (BiffException e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) throws IOException {
    ReadExcel test = new ReadExcel();
    test.setInputFile("c:/temp/lars.xls");
    test.read();
  }

} </span>
上面写的功能有点多,下面的是一部分常用的:

3 读取Excel

<span style="font-size:14px;">import java.io.File;
import java.io.IOException;
 
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
 
public class ExcelRead {
 
 
	public void read(String fname) throws BiffException, IOException{
		File f = new File(fname);
 
		Workbook workbook = Workbook.getWorkbook(f);
		Sheet sheet = workbook.getSheet(0);//读取第一个Sheet.
		int rows = 1;
		System.out.println(sheet.getRows());//读取行数
		System.out.println(sheet.getColumns());//读取列数
		System.out.println("---------------------");
 
		for(rows=0;rows<sheet.getRows();rows++){
			System.out.println("第" + (rows + 1) + "行:");
			for(int cols = 0;cols < sheet.getColumns();cols++){
				Cell ce = sheet.getCell(cols, rows); 
				System.out.print( ce.getContents() + "\t");
			}
			System.out.println("");
		}
	}
	public static void main(String[] args) throws BiffException, IOException {
		ExcelRead ER = new ExcelRead();
		String fname = "/Users/mc2/Desktop/test.xls";
		ER.read(fname);
 
		//fname = "/Users/mc2/Desktop/test.xlsx";
		//ER.read(fname);
	}
 
}</span>

4 写入Excel

import java.io.File;
import java.io.IOException;
 
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
 
public class ExcelRead {
 
 
	public void read(String fname) throws BiffException, IOException{
		File f = new File(fname);
 
		Workbook workbook = Workbook.getWorkbook(f);
		Sheet sheet = workbook.getSheet(0);//读取第一个Sheet.
		int rows = 1;
		System.out.println(sheet.getRows());//读取行数
		System.out.println(sheet.getColumns());//读取列数
		System.out.println("---------------------");
 
		for(rows=0;rows<sheet.getRows();rows++){
			System.out.println("第" + (rows + 1) + "行:");
			for(int cols = 0;cols < sheet.getColumns();cols++){
				Cell ce = sheet.getCell(cols, rows); 
				System.out.print( ce.getContents() + "\t");
			}
			System.out.println("");
		}
	}
	public static void main(String[] args) throws BiffException, IOException {
		ExcelRead ER = new ExcelRead();
		String fname = "/Users/mc2/Desktop/test.xls";
		ER.read(fname);
 
		//fname = "/Users/mc2/Desktop/test.xlsx";
		//ER.read(fname);
	}
 
}

在一个Excel文件中查找是否包含某一个关键字

<span style="font-family:Microsoft YaHei;">/**搜索某一个文件中是否包含某个关键字  
     * @param file  待搜索的文件  
     * @param keyWord  要搜索的关键字  
     * @return  
     */  
    public static boolean searchKeyWord(File file,String keyWord){   
        boolean res = false;   
           
        Workbook wb = null;   
        try {   
            //构造Workbook(工作薄)对象   
            wb=Workbook.getWorkbook(file);   
        } catch (BiffException e) {   
            return res;   
        } catch (IOException e) {   
            return res;   
        }   
           
        if(wb==null)   
            return res;   
           
        //获得了Workbook对象之后,就可以通过它得到Sheet(工作表)对象了   
        Sheet[] sheet = wb.getSheets();   
           
        boolean breakSheet = false;   
           
        if(sheet!=null&&sheet.length>0){   
            //对每个工作表进行循环   
            for(int i=0;i
                if(breakSheet)   
                    break;   
                   
                //得到当前工作表的行数   
                int rowNum = sheet[i].getRows();   
                   
                boolean breakRow = false;   
                   
                for(int j=0;j
                    if(breakRow)   
                        break;   
                    //得到当前行的所有单元格   
                    Cell[] cells = sheet[i].getRow(j);   
                    if(cells!=null&&cells.length>0){   
                        boolean breakCell = false;   
                        //对每个单元格进行循环   
                        for(int k=0;k
                            if(breakCell)   
                                break;   
                            //读取当前单元格的值   
                            String cellValue = cells[k].getContents();   
                            if(cellValue==null)   
                                continue;   
                            if(cellValue.contains(keyWord)){   
                                res = true;   
                                breakCell = true;   
                                breakRow = true;   
                                breakSheet = true;   
                            }   
                        }   
                    }   
                }   
            }   
        }   
        //最后关闭资源,释放内存   
        wb.close();   
           
        return res;   
    }  </span>
<pre code_snippet_id="111830" snippet_file_name="blog_20131214_5_4999175">
 
  
 
  
 
  
 
  
 
 


6 往Excel中插入图片图标

插入图片的实现很容易,参看以下代码:
<span style="font-family:Microsoft YaHei;font-size:12px;">/**往Excel中插入图片  
 * @param dataSheet  待插入的工作表  
 * @param col 图片从该列开始  
 * @param row 图片从该行开始  
 * @param width 图片所占的列数  
 * @param height 图片所占的行数  
 * @param imgFile 要插入的图片文件  
 */  
public static void insertImg(WritableSheet dataSheet, int col, int row, int width,   
        int height, File imgFile){   
    WritableImage img = new WritableImage(col, row, width, height, imgFile);   
    dataSheet.addImage(img);   
}   </span>

以上代码的注释已经很清楚了,大概也就不用再解释了,我们可以用如下程序验证:
<span style="font-family:Microsoft YaHei;font-size:12px;"> try {   
        //创建一个工作薄   
WritableWorkbook workbook = Workbook.createWorkbook(new File("D:/test1.xls"));   
//待插入的工作表   
WritableSheet imgSheet = workbook.createSheet("Images",0);   
//要插入的图片文件   
File imgFile = new File("D:/1.png");   
//图片插入到第二行第一个单元格,长宽各占六个单元格   
insertImg(imgSheet,0,1,6,6,imgFile);   
workbook.write();   
workbook.close();   
 catch (IOException e) {   
e.printStackTrace();   
 catch (WriteException e) {   
e.printStackTrace();   </span>

但是jxl只支持png格式的图片,jpg格式和gif格式都不支持。

7 插入页眉页脚

一般的页眉页脚都分为三个部分,左,中,右三部分,利用如下代码可实现插入页眉页脚
<span style="font-family:Microsoft YaHei;font-size:12px;">/**向Excel中加入页眉页脚  
 * @param dataSheet 待加入页眉的工作表  
 * @param left  
 * @param center  
 * @param right  
 */  
public static void setHeader(WritableSheet dataSheet,String left,String center,String right){   
    HeaderFooter hf = new HeaderFooter();   
    hf.getLeft().append(left);   
    hf.getCentre().append(center);   
    hf.getRight().append(right);   
    //加入页眉   
    dataSheet.getSettings().setHeader(hf);   
    //加入页脚   
    //dataSheet.getSettings().setFooter(hf);   
}  
</span>

我们可以用如下代码测试该方法:
<span style="font-family:Microsoft YaHei;font-size:12px;"> try {   
        //创建一个工作薄   
    WritableWorkbook workbook = Workbook.createWorkbook(new File("D:/test1.xls"));   
    //待插入的工作表   
    WritableSheet dataSheet = workbook.createSheet("加入页眉",0);   
    ExcelUtils.setHeader(dataSheet, "chb", "2007-03-06", "第1页,共3页");   
    workbook.write();   
    workbook.close();   
} catch (IOException e) {   
    e.printStackTrace();   
} catch (WriteException e) {   
    e.printStackTrace();   
}   
  }   
</span>


参考:

利用java操作Excel文件

java采用jxl读取Excel

Excel and Java - Read and Write Excel with Java

Java修改Excel单元格的数据及格式

POI对EXCEL的操作【重点:如何设置CELL格式为文本格式】(写的蛮详细,要用POI可以参考下)





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值