天天看點

poi方式寫入資料到Excel

在java資料庫程式設計中,常常會用到向excel中讀寫資料,一方面可以将資料從資料庫導出到excel,進行資料展示,另一方面可以批量的向資料庫插入多條資料,這對于軟體開發是必不可少的,今天先介紹如何使用java向excel中寫入資料,這裡以2003版本的excel版本為例,分享我的實戰經驗。(在後續的經驗中會介紹excel資料導出,敬請浏覽)

eclipse, java poi的jar包

1

導入poi的jar包

建立一個項目,在根目錄在建立一個lib檔案夾,将jar包複制粘貼到lib檔案夾後,右鍵将其添加到項目的build path中,最後的結果如圖所示:

poi方式寫入資料到Excel

2

編寫java類,建立一個實體類,比如我們要導出資料庫的有關電腦的資訊,那麼就建一個computer實體類,代碼如下:

package com.qiang.poi;

public class computer {

 private int id;

 private string name;

 private string description;

 private double price;

 private double credit;

 public int getid() {

  return id;

 }

 public computer(int id, string name, string description, double price,

   double credit) {

  super();

  this.id = id;

  this.name = name;

  this.description = description;

  this.price = price;

  this.credit = credit;

 public void setid(int id) {

 public string getname() {

  return name;

 public void setname(string name) {

 public string getdescription() {

  return description;

 public void setdescription(string description) {

 public double getprice() {

  return price;

 public void setprice(double price) {

 public double getcredit() {

  return credit;

 public void setcredit(double credit) {

}

3

建立一個寫入excel的方法,如write2excel,參數可以後面邊寫邊決定(站在一個不熟悉poi的角度)

public static void write2excel(){}                                 

4

建立操作excel的hssfworkbook對象

hssfworkbook excel= new hssfworkbook();

5

建立hssfsheet對象

excel中的一個sheet(工作表)對應着java中的一個hssfsheet對象,利用hssfworkbook對象可以建立一個hssfsheet對象

    如:建立一個sheet名為computer的excel  

hssfsheet sheet = excel.createsheet("computer");

6

建立第一行标題資訊的hssfrow對象

我們都知道excel是表格,即由一行一行組成的,那麼這一行在java類中就是一個hssfrow對象,我們通過hssfsheet對象就可以建立hssfrow對象

    如:建立表格中的第一行(我們常用來做标題的行)  hssfrow firstrow = sheet.createrow(0); 注意下标從0開始

7

建立标題行中的hssfcell數組

當然,excel中每一行是由若幹個單元格,我們常稱為cell,它對應着java中的hssfcell對象

    如:建立5個單元格       hssfcell cells[] = new hssfcell[5]; 

//假設我們一行有五列資料

8

建立标題資料,并通過hssfcell對象的setcellvalue()方法對每個單元格進行指派

既然單元格都準備好了,那最後是不是該填充資料了呀。對的,沒錯。填充資料之前,得把資料準備好吧,

    資料:string[] titles = new string[]{"id","name","description","price","credit"};

    插入一句話: 在這個時代,能讓機器做的,盡量不讓人來做,記住這句話。

    好的,繼續。現在就通過for循環來填充第一行标題的資料

for (int i = 0; i < 5; i++) {

   cells[0] = firstrow.createcell(i);

   cells[0].setcellvalue(titles[i]);

  }

9

資料分析

第一行标題欄建立完畢後,就準備填充我們要寫入的資料吧,在java中,面向對象給我們帶來的好處在這裡正好展現了,沒錯

把要填寫的資料封裝在對象中,即一行就是一個對象,n行就是一個對象清單嘛,好的,走起。

建立對象computer,私有屬性id,name,description,price,credit,以及各屬性的setter和getter方法,如步驟二所示。

假設我們要寫入excel中的資料從資料庫查詢出來的,最後就生成了一個list<computer>對象computers

10

資料寫入

具體資料有了,又該讓機器幫我們幹活了,向excel中寫入資料。

for (int i = 0; i < computers.size(); i++) {

   hssfrow row = sheet.createrow(i + 1);

   computer computer = computers.get(i);

   hssfcell cell = row.createcell(0);

   cell.setcellvalue(computer.getid());

   cell = row.createcell(1);

   cell.setcellvalue(computer.getname());

   cell = row.createcell(2);

   cell.setcellvalue(computer.getdescription());

   cell = row.createcell(3);

   cell.setcellvalue(computer.getprice());

   cell = row.createcell(4);

   cell.setcellvalue(computer.getcredit());

11

将資料真正的寫入excel檔案中

做到這裡,資料都寫好了,最後就是把hssfworkbook對象excel寫入檔案中了。

        outputstream out = null;

        try {

            out = new fileoutputstream(file);

            excel.write(out);

            out.close();

        } catch (filenotfoundexception e) {

            e.printstacktrace();

        } catch (ioexception e) {

            // todo auto-generated catch block

        }

        system.out.println("資料已經寫入excel"); //溫馨提示

12

看看我的main方法吧

public static void main(string[] args) throws ioexception {

  file file = new file("test1.xls");

  if(!file.exists()){

   file.createnewfile();

  list<computer> computers = new arraylist<computer>();

  computers.add(new computer(1,"宏碁","筆記本電腦",3333,9.0));

  computers.add(new computer(2,"蘋果","筆記本電腦,一體機",8888,9.6));

  computers.add(new computer(3,"聯想","筆記本電腦,桌上型電腦",4444,9.3));

  computers.add(new computer(4, "華碩", "筆記本電腦,平闆電腦",3555,8.6));

  computers.add(new computer(5, "注解", "以上價格均為捏造,如有雷同,純屬巧合", 1.0, 9.9));

  write2excel(computers, file);

13

工程目錄及執行main方法後的test1.xls資料展示

poi方式寫入資料到Excel
poi方式寫入資料到Excel

14

源碼分享,computer就不貼了

import java.io.file;

import java.io.filenotfoundexception;

import java.io.fileoutputstream;

import java.io.ioexception;

import java.io.outputstream;

import java.util.arraylist;

import java.util.list;

import org.apache.poi.hssf.usermodel.hssfcell;

import org.apache.poi.hssf.usermodel.hssfrow;

import org.apache.poi.hssf.usermodel.hssfsheet;

import org.apache.poi.hssf.usermodel.hssfworkbook;

public class readexcel {

 public static void main(string[] args) throws ioexception {

 public static void write2excel(list<computer> computers,file file) {

  hssfworkbook excel = new hssfworkbook();

  hssfsheet sheet = excel.createsheet("computer");

  hssfrow firstrow = sheet.createrow(0);

  hssfcell cells[] = new hssfcell[5];

  string[] titles = new string[] { "id", "name", "description", "price",

    "credit" };

  for (int i = 0; i < 5; i++) {

  for (int i = 0; i < computers.size(); i++) {

        outputstream out = null;

        try {

            out = new fileoutputstream(file);

            excel.write(out);

            out.close();

        } catch (filenotfoundexception e) {

            e.printstacktrace();

        } catch (ioexception e) {

        }