Java讀取Excel檔案,生成SQL語句
阿新 • • 發佈:2019-01-22
import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; import java.io.*; public class Main { public static void main(String[] args) { Main obj = new Main(); File file = new File("D:\\工作表1.xls"); obj.readExcel(file); } // 去讀Excel的方法readExcel,該方法的入口引數為一個File物件 public void readExcel(File file) { try { // 建立輸入流,讀取Excel InputStream is = new FileInputStream(file.getAbsolutePath()); // jxl提供的Workbook類 Workbook wb = Workbook.getWorkbook(is); // Excel的頁籤數量 int sheet_size = wb.getNumberOfSheets(); for (int index = 0; index < sheet_size; index++) { // 每個頁籤建立一個Sheet物件 Sheet sheet = wb.getSheet(index); // sheet.getRows()返回該頁的總行數 StringBuilder sb = new StringBuilder(); String str1 = ""; String str2 = ""; String str3 = ""; int count = 0; for (int i = 0; i < sheet.getColumns(); i++) { // sheet.getColumns()返回該頁的總列數 ++count; for (int j = 0; j < sheet.getRows(); j++) { String cellinfo = sheet.getCell(i, j).getContents(); if (j == 0) { str1 = cellinfo; } else if (j == 1) { str2 = cellinfo; } else { str3 = cellinfo; } } sb.append(str1).append(" ").append(str3).append(" ").append("comment").append("'").append(str2).append("'").append(","); System.out.println(sb.toString()); sb.setLength(0); str1 = ""; str2 = ""; str3 = ""; } System.out.println("總欄位數:"+count); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (BiffException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } //id int comment'主鍵id', //name varchar comment'姓名', //age int comment'年齡', //總欄位數:3 //總欄位數:0 //總欄位數:0
注意;jxl只能解析.xls格式的表格
如果欄位較多,可以直接生成SQL語句