1、添加POI jar包到項目的lib目錄下
2、Excel檔案目錄:d://excel.xls
3、資料庫欄位為:num1 num2 num3 num4 num5 num6
4、資料庫名:blog
5、表名:test
6、編寫類:串連mysql的字串方法、插入的方法、實體類
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class TestExcel {
//記錄類的輸出資訊
static Log log = LogFactory.getLog(TestExcel.class);
//擷取Excel文檔的路徑
public static String filePath = "D://excel.xls";
public static void main(String[] args) {
try {
// 建立對Excel活頁簿檔案的引用
HSSFWorkbook wookbook = new HSSFWorkbook(new FileInputStream(filePath));
// 在Excel文檔中,第一張工作表的預設索引是0
// 其語句為:HSSFSheet sheet = workbook.getSheetAt(0);
HSSFSheet sheet = wookbook.getSheet("Sheet1");
//擷取到Excel檔案中的所有行數
int rows = sheet.getPhysicalNumberOfRows();
//遍曆行
for (int i = 0; i < rows; i++) {
// 讀取左上端儲存格
HSSFRow row = sheet.getRow(i);
// 行不為空白
if (row != null) {
//擷取到Excel檔案中的所有的列
int cells = row.getPhysicalNumberOfCells();
String value = "";
//遍曆列
for (int j = 0; j < cells; j++) {
//擷取到列的值
HSSFCell cell = row.getCell(j);
if (cell != null) {
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_FORMULA:
break;
case HSSFCell.CELL_TYPE_NUMERIC:
value += cell.getNumericCellValue() + ",";
break;
case HSSFCell.CELL_TYPE_STRING:
value += cell.getStringCellValue() + ",";
break;
default:
value += "0";
break;
}
}
}
// 將資料插入到mysql資料庫中
String[] val = value.split(",");
TestEntity entity = new TestEntity();
entity.setNum1(val[0]);
entity.setNum2(val[1]);
entity.setNum3(val[2]);
entity.setNum4(val[3]);
entity.setNum5(val[4]);
entity.setNum6(val[5]);
TestMethod method = new TestMethod();
method.Add(entity);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}