ReadExcel类:
package com.linbilin.readExcel;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
/**
* @author Lin
*
*/
public class ReadExcel {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
Connection conn=DbUtil.getConnection("jdbc:oracle:thin:@192.168.9.26:1521:orcl","test", "test", DbUtil.ORACLE_DRIVER);
FileInputStream fileIn = new FileInputStream(
"C:\Users\Desktop\数据项集v1.2.xls");
Workbook wb = new HSSFWorkbook(new POIFSFileSystem(fileIn));
int numOfSheets = wb.getNumberOfSheets();
Sheet sheet = null;
Row row = null;
Cell cell = null;
String cellValue = "";
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Map map = null;
FileWriter fileWrite = new FileWriter(
"C:\Users\Desktop\记录.txt");
// 循环遍历
for (int indexOfSheet = 1; indexOfSheet < numOfSheets; indexOfSheet++) {
sheet = wb.getSheetAt(indexOfSheet);
for (int indexOfRowNum = sheet.getFirstRowNum() + 1, rowNum = sheet
.getLastRowNum(); indexOfRowNum <= rowNum; indexOfRowNum++) {
System.out.println("行" + indexOfRowNum);
row = sheet.getRow(indexOfRowNum);
if (row != null) {
if (row.getCell(0).getStringCellValue().isEmpty()) {
continue;
} else {
map = new LinkedHashMap<String, String>();
for (int indexOfCell = 0; indexOfCell <= 5; indexOfCell++) {
System.out.println("列" + indexOfCell);
cell = row.getCell(indexOfCell);
if (cell != null) {
cellValue = getCellValue(cell);
fileWrite.write(cellValue + "\r\n");
map.put(indexOfCell + "", cellValue);
}
}
if (!map.isEmpty()) {
list.add(map);
}
}
}
}
}
DbUtil.insertDataItem(conn, list);
//System.out.println(list);
// 关闭流
fileWrite.flush();
fileWrite.close();
fileIn.close();
wb.close();
}
public static String getCellValue(Cell cell) {
int cellType = cell.getCellType();
String cellValue = "";
switch (cellType) {
case HSSFCell.CELL_TYPE_NUMERIC:
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_FORMULA:
try {
cellValue = cell.getStringCellValue();
} catch (IllegalStateException e) {
cellValue = String.valueOf(cell.getNumericCellValue());
}
break;
default:
cellValue = cell.getStringCellValue();
}
return cellValue.trim();
}
}
package com.linbilin.readExcel