1. 程式人生 > >JAVA處理Excel表格資料並寫入資料庫

JAVA處理Excel表格資料並寫入資料庫

        Excel提供了把SQLServer作為資料來源匯入資料的技術,但似乎沒有提供方法把Excel中的資料匯入到資料庫。Apache的POI提供了Java程式對Microsoft Office格式檔案讀和寫的功能。

基本功能:

                XSSF - 提供讀寫Microsoft Excel OOXML格式檔案的功能。

                HSLF - 提供讀寫Microsoft PowerPoint格式檔案的功能。

匯入jar包:

                

下面就可以解析excel文件了:   

package com.hncj.test;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.junit.Test;

public class ExcelReader {

        //獲取資料庫連線
	public static Connection getConnection() throws Exception {
		Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
		Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=JWGL", "sa", "112233");
		return connection;
	}
	
	
	public static void main(String[] args) {
		try {
                        //獲取excel檔案的輸入流,必須是.xls字尾,如果是xlsx字尾,要用XSSFWorkBook
			FileInputStream fis = new FileInputStream("src/info.xls");
			HSSFWorkbook hssfWorkbook = new HSSFWorkbook(fis);
                        //獲取表格
			HSSFSheet sheetAt = hssfWorkbook.getSheetAt(0);
			Connection connection = getConnection();
			String sql = "insert into XS values(?,?,?,?,?)";
			PreparedStatement ps = connection.prepareStatement(sql);
                        //遍歷每行及每個單元格
			for (Row row : sheetAt) {
                                //每個單元格有不同的數值型別,具體可以通過cell的getCellType()方法檢視
				ps.setString(1, row.getCell(0).getStringCellValue().toString());
				ps.setString(2, row.getCell(1).getStringCellValue().toString());
				ps.setInt(3, (int)row.getCell(2).getNumericCellValue());
				ps.setString(4, row.getCell(3).getStringCellValue().toString());
				ps.setString(5, row.getCell(4).getStringCellValue().toString());
				ps.execute();
			}
			ps.close();
			connection.close();
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}