实验环境:windows8.1,eclipse4.4, jre8
需要jar包:若是.xls格式,可用jxl.jar,下载;若是.xlsx格式,使用poi,下载
1..xls格式
写文件
public void writeXls(String filepath) {
try {
WritableWorkbook book = Workbook.createWorkbook(new File(filepath));
WritableSheet sheet = book.createSheet("first_sheet", 0);
jxl.write.Number number = null;
for (int i = 0; i < 5; i++) {// 5行
for (int j = 0; j < 3; j++) {// 3列
number = new jxl.write.Number(j, i, i + j);
sheet.addCell(number);
}
}
book.write();
book.close();
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
读文件
public void readXls(String filepath) {
jxl.Workbook readwb = null;
try {
// 构建Workbook对象, 只读Workbook对象
// 直接从本地文件创建Workbook
InputStream instream = new FileInputStream(filepath);
readwb = Workbook.getWorkbook(instream);
// Sheet的下标是从0开始
// 获取第一张Sheet表
Sheet readsheet = readwb.getSheet(0);
// 获取Sheet表中所包含的总列数
int rsColumns = readsheet.getColumns();
// 获取Sheet表中所包含的总行数
int rsRows = readsheet.getRows();
Cell cell = null;
String line = "";
// 获取指定单元格的对象引用 ,从第一行第一列开始,即非说明数据
for (int i = 0; i < rsRows; i++) {
for (int j = 0; j < rsColumns; j++) {
cell = readsheet.getCell(j, i);
line = line + "\t" + cell.getContents();
}
System.out.println(line);
line = "";
}
} catch (Exception e) {
e.printStackTrace();
} finally {
readwb.close();
}
}
2..xlsx格式
写文件
public void writeXlsx(String filepath) {
XSSFWorkbook wb = null;
try {
// 构建Workbook对象, 只读Workbook对象
// 直接从本地文件创建Workbook
wb = new XSSFWorkbook();
// Sheet的下标是从0开始
// 获取第一张Sheet表
XSSFSheet sheet = wb.createSheet("fist_sheet");
// 设置Sheet表中所包含的总行数
int rsRows = 5;
// 设置Sheet表中所包含的总列数
int rsColumns = 3;
// 从第0行第0列开始
for (int i = 0; i < rsRows; i++) {
XSSFRow row = sheet.createRow(i);
for (int j = 0; j < rsColumns; j++) {
XSSFCell cell = row.createCell(j);
// String data = new CellReference(cell).formatAsString();
cell.setCellValue("test_" + i + j);
}
}
FileOutputStream os = new FileOutputStream(filepath);
wb.write(os);
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
读文件
public void readXlsx(String filepath) {
XSSFWorkbook readwb = null;
try {
// 构建Workbook对象, 只读Workbook对象
// 直接从本地文件创建Workbook
readwb = new XSSFWorkbook(new FileInputStream(filepath));
// Sheet的下标是从0开始
// 获取第一张Sheet表
XSSFSheet readsheet = readwb.getSheetAt(0);
// 获取Sheet表中所包含的总行数
int rsRows = readsheet.getPhysicalNumberOfRows();
XSSFRow row = null;
String line = "";
// 获取指定单元格的对象引用 ,从第一行第一列开始,即非说明数据
for (int i = 0; i < rsRows; i++) {
row = readsheet.getRow(i);
// 获取Sheet表中所包含的总列数
int rsColumns = row.getPhysicalNumberOfCells();
for (int j = 0; j < rsColumns; j++) {
line = line + "\t" + row.getCell(j).toString();
}
System.out.println(line);
line = "";
}
readwb.close();
} catch (Exception e) {
e.printStackTrace();
}
}