jxl操作excel
阿新 • • 發佈:2019-02-16
java程式碼
package exc; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; public class SgaqglddUtil { /** * * 函式功能說明 :讀取excel * @param path * @throws */ public static void read(String path){ try { Workbook book = Workbook.getWorkbook( new File( path )); // 獲得第一個工作表物件 Sheet sheet = book.getSheet( 0 ); // 得到第一列第一行的單元格 Cell cell1 = sheet.getCell( 0 , 0 ); String result = cell1.getContents(); System.out.println(result); book.close(); } catch (Exception e) { System.out.println(e); } } public static void write(String path){ try { // Excel獲得檔案 Workbook wb = Workbook.getWorkbook( new File(path)); // 開啟一個檔案的副本,並且指定資料寫回到原檔案 WritableWorkbook book = Workbook.createWorkbook( new File(path), wb); WritableSheet sheet1=book.getSheet(0); // 獲取第一個工作表 // WritableSheet sheet = book.createSheet( " 第二頁 " , 1 );//建立一個工作表 int y=0,x=1; sheet1.addCell( new Label( y , x, "測試資料 "));//在第向x+1行,y+1列新增“測試資料” book.write(); book.close(); } catch (Exception e) { System.out.println(e); } } public static void main(String args[]) throws IOException { String path="E:\\bb.xls"; SgaqglddUtil.copyFile(path, "E:\\excel\\b2.xls"); SgaqglddUtil.write(path); SgaqglddUtil.read(path); } // 複製檔案 public static void copyFile(String sourceFile, String targetFile) throws IOException { // File file=new File(targetFile); // file.mkdirs(); BufferedInputStream inBuff = null; BufferedOutputStream outBuff = null; try { // 新建檔案輸入流並對它進行緩衝 inBuff = new BufferedInputStream(new FileInputStream(sourceFile)); // 新建檔案輸出流並對它進行緩衝 outBuff = new BufferedOutputStream(new FileOutputStream(targetFile)); // 緩衝陣列 byte[] b = new byte[1024 * 5]; int len; while ((len = inBuff.read(b)) != -1) { outBuff.write(b, 0, len); } // 重新整理此緩衝的輸出流 outBuff.flush(); } finally { // 關閉流 if (inBuff != null) inBuff.close(); if (outBuff != null) outBuff.close(); } } }