將數據寫入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();
}
}