Java通过jxl读Excel,唯一前提:引入jxl.jar包。
package com.neusoft.excel;
import java.io.File;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
/**
* jxl读excel
*
* @author jianggujin
*
*/
public class ReadExcel {
public static void main(String[] args) throws Exception {
String filepath = "D:\\data";
File file = new File(filepath);
if (file.isDirectory()) {
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
File readfile = new File(filepath + "\\" + filelist[i]);
if (!readfile.isDirectory()) {
System.out.println("第【"+(i+1)+"】个文件:" + readfile.getName());
readExcel(readfile);
//break;
}
}
System.out.println("执行完毕");
}
}
public static void readExcel(File xlsFile) throws Exception {
// 获得工作簿对象
Workbook workbook = Workbook.getWorkbook(xlsFile);
// 获得所有工作表
Sheet[] sheets = workbook.getSheets();
// 遍历工作表
if (sheets != null) {
for (Sheet sheet : sheets) {
// 获得行数
int rows = sheet.getRows();
// 获得列数
int cols = sheet.getColumns();
String name = "";
String sex = "";
String id = "";
String comp = "";
// 读取数据
for (int row = 1; row < rows; row++) {
for (int col = 0; col < cols; col++) {
System.out.printf("%10s", sheet.getCell(col, row).getContents());
if (col == 1) {
name = sheet.getCell(col, row).getContents();
}
if (col == 2) {
sex = sheet.getCell(col, row).getContents();
}
if (col == 4) {
id = sheet.getCell(col, row).getContents();
}
if (col == 5) {
comp = sheet.getCell(col, row).getContents();
}
}
writeExcel(name, sex, id, comp);
System.out.println();
}
}
}
workbook.close();
}
public static void writeExcel(String name, String sex, String id, String comp) throws Exception {
File xlsFile = new File("demo.xls");
Workbook book = Workbook.getWorkbook(xlsFile);
// 创建一个工作簿
WritableWorkbook workbook = Workbook.createWorkbook(xlsFile, book);
// 创建一个工作表
WritableSheet sheet = workbook.getSheet(0);
int rows = sheet.getRows();
System.out.println(rows);
// for (int row = rows; row < 20; row++) {
// for (int col = 0; col < 10; col++) {
// 向工作表中添加数据
sheet.addCell(new Label(1, rows, name));
sheet.addCell(new Label(2, rows, sex));
sheet.addCell(new Label(6, rows, id));
sheet.addCell(new Label(12, rows, comp));
// }
// }
workbook.write();
workbook.close();
}
}