java產生excel和讀取excel例子

來源:互聯網
上載者:User

標籤:java產生excel和讀取excel

關於使用java的操作excel的方法有很多種,我的http://blog.csdn.net/qq_20545159/article/details/45132041價紹過,下面是使用jxl產生xls格式的excel簡單的代碼。

使用jxl產生excel檔案首先必須將jxl.jar的包加到你的項目的路徑下。

package com.silence.excel;
import java.io.File;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class jxlExcel {

public static void main(String[] args) {
// 設定該表格的列標籤
String[] title = { "id", "name", "age", "sex", "number" };
// 建立檔案
File file = new File("e:\\temp.xls");
try {
if (!file.exists()) {
file.createNewFile();
}
// 建立工作普
WritableWorkbook workbook = Workbook.createWorkbook(file);
// 建立sheet
WritableSheet sheet = workbook.createSheet("sheet0", 0);
Label label = null;
// 設定一行列名
for (int i = 0; i < title.length; i++) {
label = new Label(i, 0, title[i]);
sheet.addCell(label);
}
// 迴圈向每一行中插入資料
for (int i = 0; i < 10; i++) {
label = new Label(0, i, "user" + i);
sheet.addCell(label);
label = new Label(1, i, "張三" + i);
sheet.addCell(label);
label = new Label(2, i, 21 +i+"");
sheet.addCell(label);
label = new Label(3, i, "a" + i);
sheet.addCell(label);
label = new Label(4, i, "silencewaking in the sun " + i);
sheet.addCell(label);

}

                       //結束

workbook.write();
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}

}

java讀取excel
package com.silence.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 jxlReadExcel {
  
public static void main(String[] args) {
 
try {
//建立workbook
Workbook workbook  = Workbook.getWorkbook(new File("e:\\temp.xls"));
//擷取工作表sheet
Sheet sheet = workbook.getSheet(0);
for (int i = 0; i < sheet.getRows(); i++) {
for (int j = 0; j < sheet.getColumns(); j++) {
Cell cell = sheet.getCell(j,i);
System.out.print(cell.getContents()+" ");
}
System.out.println();
}
//擷取資料
workbook.close();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
   }

}




java產生excel和讀取excel例子

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.