2014-10-01 43 views
1

我正在開發帶有數據庫的web應用程序,用戶可以將.csv文件上傳到數據庫,它有一段時間有數據上傳的問題。所以我需要知道如何上傳excel文件到MySQL表下面的代碼如何將excel數據上傳到mysql表中

conv = new Connectivity(); 
           con = conv.setConnection(); 
           st = con.createStatement(); 
           query = "LOAD DATA LOCAL INFILE \"" + filename2 + "\" INTO TABLE " + tablename + " FIELDS TERMINATED BY ',' IGNORE 1 LINES"; 

           st.executeUpdate(query); 
           PrintWriter obj1 = response.getWriter(); 
           obj1.println("Row (1) inserted"); 

           HttpSession sval = request.getSession(); 
           sval.setAttribute("UpdatedCorret", "yes"); 
+0

什麼是你的代碼錯誤?任何例外..? – Jens 2014-10-01 11:38:31

+0

@Jens它工作正常,但有時在將excel文件轉換爲.csv文件時出現問題 – KVK 2014-10-01 11:39:59

+0

如此簡單的人...只是使用Poi API .. – Gopal00005 2014-10-01 11:40:07

回答

1

這是用POI API來解析excel文件的演示代碼...

File source = jFileChooser.getSelectedFile(); 

InputStream input = new BufferedInputStream(new FileInputStream(
       source.getCanonicalPath())); 

POIFSFileSystem fs = new POIFSFileSystem(input); 
HSSFWorkbook wb = new HSSFWorkbook(fs); 
HSSFSheet sheet = wb.getSheetAt(0); 
Iterator<?> rows = sheet.rowIterator(); 
while (rows.hasNext()) { 
    HSSFRow row = (HSSFRow) rows.next(); 
     Iterator<?> cells = row.cellIterator(); 
     while (cells.hasNext()) { 
      HSSFCell cell = (HSSFCell) cells.next(); 
      try { 
       System.out.print(new BigDecimal(cell 
        .getNumericCellValue()).toPlainString()); 
      } catch (IllegalStateException ex) { 
       System.out.print(cell.getStringCellValue()); 
      } catch (Exception ex) { 
       ex.printStackTrace(); 
     } 
    } 
} 

希望它爲你工作...

+0

好吧我明白我在哪裏可以給我的數據庫查詢 – KVK 2014-10-01 11:48:02

0

嘗試Excel2MySQL。它具有用於手動導入的簡單用戶界面,並且還包括用於自動上載的command line interface,並且可以直接讀取任何excel文件。不需要導出爲csv文件。 Excel sheetname確定目標MySQL表名。該表可以自動創建或簡單地附加到。所有字段也可以自動優化爲正確的MySQL類型。該程序可以自由嘗試,我是作者。

-h, --help, display help message and exit 
-f file, Excel file to convert (include full path) (REQUIRED) 
-s sheet, Excel sheet to convert (omit to convert all) 
-z host, mysql server hostname or IP address (omit will default to localhost) 
-d database, mysql database name (REQUIRED) 
-u user, mysql user name (REQUIRED) 
-p password, mysql password 
-x port, mysql port number (omit will default to 3306) 
-r, replace existing table (omit to append to existing table) 
-n, first row is not a header (omit to indicate first row contains header) 
-a, allow spaces in table & field names (omit to change spaces to underscores) 
-m, use myisam database storage engine (omit to use innodb) 
-k, keep blank rows & columns (omit to remove) 
-c, Unmerge merged cells 
-v, define all fields as varchar type on tables (omit to optimize field types) 

下面是一個示例命令行上傳的Excel與「地址」的表文件的文件名:

excel2mysqlCLI.exe -f "c:\my excel.xls" -d mydb -u myid -p mypass -s address 
相關問題