public static void text() {
String finalXlsxPath = "C:\\test.xlsx";
File file = new File(finalXlsxPath);
//定義輸入流對象
FileInputStream excelFileInputStream;
try {
excelFileInputStream = new FileInputStream(file);
// 拿到文件轉化爲JavaPoi可操縱類型
Workbook workbook = WorkbookFactory.create(excelFileInputStream);
excelFileInputStream.close();
////獲取excel表格
Sheet sheet = workbook.getSheetAt(0);
//獲取單元格的row和cell
// 獲取行
String x = sheet.getRow(6).getCell(0).toString();
Row row = sheet.getRow(6);
// 獲取列
row.createCell(4);
Cell cell = row.getCell(4);
//設置單元的值
cell.setCellValue(x);
sheet = workbook.getSheetAt(1);//獲取第二張工作表
Row currentrow = sheet.getRow(1);//獲取第二行
Cell currentcell = currentrow.createCell(1);//創建並在第二個單元格中寫入數據
currentcell.setCellValue(median);
currentrow = sheet.getRow(2);
currentcell = currentrow.createCell(1);
currentcell.setCellValue(division);
currentrow = sheet.getRow(3);
currentcell = currentrow.createCell(1);
currentcell.setCellValue(numOfK);
//寫入數據
FileOutputStream excelFileOutPutStream = new FileOutputStream(file);
workbook.write(excelFileOutPutStream);
excelFileOutPutStream.flush();
excelFileOutPutStream.close();
System.out.println("指定單元格設置數據寫入完成");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (EncryptedDocumentException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("數據導出成功");
}
public static Workbook getWorkbok(File file) throws IOException{
Workbook wb = null;
FileInputStream in = new FileInputStream(file);
if(file.getName().endsWith(EXCEL_XLS)){ //Excel 2003
wb = new HSSFWorkbook(in);
}else if(file.getName().endsWith(EXCEL_XLSX)){ // Excel 2007/2010
wb = new XSSFWorkbook(in);
}
return wb;
}