Java實現對Excel檔案匯入匯出
阿新 • • 發佈:2019-01-23
1.匯入jar包
2.建立entity類
public class Book { private String name; private double price; private String author; public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public Book() { super(); // TODO Auto-generated constructor stub } public Book(String name, double price, String author) { super(); this.name = name; this.price = price; this.author = author; } @Override public String toString() { return "Book [name=" + name + ", price=" + price + ", author=" + author + "]"; } }
3.匯出Excel檔案
public void ExcelExp(){ //新增元素 List<Book> list = new ArrayList<Book>(); Book book1 = new Book("西遊記", 99.0, "吳承恩"); Book book2 = new Book("三國演義", 79.0, "羅貫中"); Book book3 = new Book("紅樓夢", 89.0, "曹雪芹"); Book book4 = new Book("水滸傳", 109.0, "施耐庵"); list.add(book1); list.add(book2); list.add(book3); list.add(book4); //設定輸出檔案路徑 String url = "G:/book.xlsx"; Workbook wb = null; try { OutputStream os = new FileOutputStream(url); wb = new XSSFWorkbook(); //獲取選項卡 Sheet sheet = wb.createSheet("Sheet1"); //獲取第一行,對第一行設定標籤 Row row = sheet.createRow(0); row.createCell(0).setCellValue("書名"); row.createCell(1).setCellValue("價格"); row.createCell(2).setCellValue("作者"); //迴圈遍歷列表,將所有資料儲存到行內 for(int i=0;i<list.size();i++){ Book books = list.get(i); Row rows = sheet.createRow(i+1); rows.createCell(0).setCellValue(books.getName()); rows.createCell(1).setCellValue(books.getPrice()); rows.createCell(2).setCellValue(books.getAuthor()); } //匯出檔案 wb.write(os); } catch (Exception e) { e.printStackTrace(); } }
4.匯入 Excel檔案
@Test public void ExcelImp(){ //設定讀取Excel檔案路徑 String url = "G:/book.xlsx"; Workbook wb = null; try { InputStream is = new FileInputStream(url); wb = new XSSFWorkbook(is); //獲取指定選項卡 Sheet sheet = wb.getSheet("sheet1"); //獲取資料的總行數 int line = sheet.getLastRowNum(); //遍歷,不獲取第一行便籤 for(int i=1;i<=line;i++){ String name = sheet.getRow(i).getCell(0).getStringCellValue(); double price = sheet.getRow(i).getCell(1).getNumericCellValue(); String autor = sheet.getRow(i).getCell(2).getStringCellValue(); //輸出Excel檔案內容 System.out.println(new Book(name,price,autor)); } } catch (Exception e) { e.printStackTrace(); } }
5.對於包的匯入
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
6.大致流程