- 论坛徽章:
- 0
|
最近用到通过Excel导入数据到数据库的比较多,整理了一个简单实用的通过jxl.jar读取Excel文件的类:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import jxl.Cell;
import jxl.CellType;
import jxl.DateCell;
import jxl.NumberCell;
import jxl.Sheet;
import jxl.Workbook;
import org.apache.log4j.Logger;
public class ExcelTool {
private static final String ENCODE_WHEN_READING = "GBK";
public static final Logger log4gm = LoggerManager.getLog();
public ExcelTool() {
}
public Workbook getExcel(InputStream is) {
Workbook wb = null;
try {
wb = Workbook.getWorkbook(is);
} catch (Exception e) {
log4gm.error(e.toString());
}
return wb;
}
public Workbook getExcel(String path) {
Workbook wb = null;
try {
InputStream is = new FileInputStream(new File(path));
wb = Workbook.getWorkbook(is);
} catch (Exception e) {
log4gm.error(e.toString());
}
return wb;
}
public Sheet[] getEachSheet(Workbook wb) {
if(null!=wb) {
return wb.getSheets();
}else {
return null;
}
}
public int findColIndex(Sheet st,String strHeadColContents) {
int intIndex = 0;
for (int i = 0; i st.getColumns(); i++) {
String strCon = st.getCell(i,0).getContents().toString().trim();
if(strHeadColContents.equals(strCon)) {
intIndex = i;
}
}
return intIndex;
}
public String getValueAt(Sheet st, int rowIndex, int colIndex) {
String strValueAt = "";
if(null != st.getCell(colIndex,rowIndex)) {
Cell cellUnit = st.getCell(colIndex,rowIndex);
if(null != cellUnit.getContents().trim()
&& !"".equals(cellUnit.getContents().toString().trim())) {
if(cellUnit.getType()==CellType.NUMBER ||
cellUnit.getType()==CellType.NUMBER_FORMULA) {
NumberCell nc=(NumberCell)cellUnit;
strValueAt = ""+nc.getValue();
}else if(cellUnit.getType()==CellType.DATE ||
cellUnit.getType()==CellType.DATE_FORMULA){
DateCell dt =(DateCell)cellUnit;
strValueAt = new SimpleDateFormat("yyyy-MM-dd").format(dt);
}else {
try {
String temp = cellUnit.getContents().trim();
strValueAt = new String(temp.getBytes(),ENCODE_WHEN_READING).trim();
} catch (Exception e) {
log4gm.error(e.toString());
}
}
}
}
return strValueAt;
}
public String[][] getTableInSheet(Sheet st,int rowStart,int columnStart,int rowMinus) {
String[][] strContents = null;
int intActualRows = st.getRows()-rowStart-rowMinus;
int intActualCols = st.getColumns()-columnStart;
strContents = new String[intActualRows][intActualCols];
for (int i = 0; i intActualRows; i++) {
for (int j = 0; j intActualCols; j++) {
strContents[j] = getValueAt(st,(i+rowStart),(j+columnStart));
}
}
return strContents;
}
}
需要用到的jar:
![]()
文件:
jxl.zip
大小:
644KB
下载:
下载
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/32417/showart_480625.html |
|