将dbf格式的文件导入到excel中

public class DBFtoExcel {

/**
* 从dbf文件中读取数据,并将数据保存到headName,data中。
* @param filePath dbf文件的位置
* @param headName 字段名称集合
* @param data 数据集合
*/
public void readDBFFile(String filePath,List headName,List data) {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(filePath);
DBFReader reader = new DBFReader(inputStream);
int numberOfFields = reader.getFieldCount();
DBFField filed = null;
for (int i = 0; i < numberOfFields; i++) {
filed = reader.getField(i);//读字段值
headName.add(new String(filed.getName()));
}
Object[] rowObjects = null;
while ((rowObjects = reader.nextRecord()) != null) { //读数据
data.add(rowObjects);
}

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

/**
* 将从dbf文件读取的数据保存成excel
* @param saveFilePath 文件保存的路径
* @param sheetNamePosts excel表中sheet名字和顺序位置
* @param headName 字段名称集合
* @param data 数据集合
*/
public void writeExcel(String saveFilePath,String[] sheetNamePosts,List headName,List data){
WritableWorkbook book = null;
try {
book = Workbook.createWorkbook(new File(saveFilePath));
Label label = null;
WritableSheet sheet = null;//工作表
Object[] rowObjects = null;
String[] sheetNamePost = null;//工作表的名字和位置
for (int i = 0; i < sheetNamePosts.length; i++) {
sheetNamePost = sheetNamePosts[i].split(":");
sheet = book.createSheet(sheetNamePost[0], Integer.parseInt(sheetNamePost[1]));//创建一个工作表
for (int j = 0; j < headName.size(); j++) {
//Label(列号,行号 ,内容)
label = new Label(j,0,new String(headName.get(j).toString().getBytes("ISO-8859-1"),"GBK"));
sheet.addCell(label);
}
for (int j = 0; j < data.size(); j++) {
rowObjects = (Object[]) data.get(j);
for (int k = 0; k < rowObjects.length; k ++) {
//Label(列号,行号 ,内容)
label = new Label(k,j+1,rowObjects[k] == null ? "" : new String(rowObjects[k].toString().getBytes("ISO-8859-1"),"GBK"));
sheet.addCell(label);
}
}
}
book.write();
} catch (IOException e) {
e.printStackTrace();
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
} finally {
if (book != null) {
try {
book.close();
} catch (WriteException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

public static void main(String[] args) {
DBFtoExcel toExcel = new DBFtoExcel();
String filePath = "F:\\dbffile\\13-s.dbf";
List headName = new ArrayList();
List data = new ArrayList();
String saveFilePath = "f:\\dbffile\\测试dbfData.xls";
String[] sheetNamePosts = {"第一页:0"};
toExcel.readDBFFile(filePath, headName, data);
toExcel.writeExcel(saveFilePath, sheetNamePosts, headName, data);
}

}

[color=blue]备注:javadbf源码见附件[/color]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值