将数据写入excel
public void WriteExcel() {
HSSFWorkbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("jack");
sheet.setDefaultColumnWidth(15);
sheet.setDefaultRowHeight((short) 300);
for (int i = 0; i < 10; i++) {
Row row = wb.getSheet("jack").createRow(i);
for (int j = 0; j < 10; j++) {
row.createCell(j).setCellValue(j*i);
}
}
FileOutputStream out = null;
try {
out = new FileOutputStream("f:\\text.xls");
wb.write(out);
} catch (IOException e) {
System.out.println(e.toString());
} finally {
try {
out.close();
} catch (IOException e) {
System.out.println(e.toString());
}
}
}
从excel读取数据
public void ReadExcel(String fileName) {
boolean isXlsx = false; // 判断是否是xlsx格式
if (fileName.endsWith("xlsx"))
isXlsx = true;
try {
InputStream input = new FileInputStream(fileName); // 建立输入流
Workbook wb = null;
if (isXlsx) {
wb = new XSSFWorkbook(input);
} else {
wb = new HSSFWorkbook(input);
}
Sheet sheet = wb.getSheetAt(0); // 获得第一个表单
for (int rowNum = 7; rowNum <= sheet.getLastRowNum(); rowNum++) {
Row hssfRow = sheet.getRow(rowNum);
System.out.println(hssfRow.getCell(2));
System.out.println(hssfRow.getCell(1));
break;
}
} catch (IOException ex) {
ex.printStackTrace();
}
}