我是Selenium Web自动化的新手,请对我说软。
我创建了一种将数组内容写入Excel工作表的方法。 我没有异常或错误,我没有看到数据被写入excel表。
excel sheet-mysheet.xlsx的名称 excel工作簿中的工作表名称:“FirstLevelMenu”
public class WriteExcelData {
XSSFWorkbook wb;
XSSFSheet sheet;
public void writeData(String path, String sheetName, String[] data) {
try {
File src = new File(path);
FileInputStream fis = new FileInputStream(src);
wb = new XSSFWorkbook(fis);
sheet = wb.getSheet(sheetName);
int rowCount = sheet.getLastRowNum() - sheet.getFirstRowNum();
Row row = sheet.getRow(0);
Row newRow = sheet.createRow(rowCount + 1);
for (int j = 0; j < row.getLastCellNum(); j++) {
Cell col = newRow.createCell(j);
col.setCellValue(data[j]);
}
fis.close();
FileOutputStream fout = new FileOutputStream(src);
wb.write(fout);
fout.close();
} catch (Exception e) {
e.getMessage();
}
}
public static void main(String[] args) {
WriteExcelData test=new WriteExcelData();
String[] data=new String[2];
data[0]="cat";
data[1]="cat";
test.writeData("C:\\mysheet.xlsx", "FirstLevelMenu", data);
}
}
答案 0 :(得分:2)
当您使用新的xlsx工作表编写时,请尝试以下代码...我相信它会起作用:)
public static void main(String[] args) throws InvalidFormatException, IOException{
FileInputStream fis=new FileInputStream("D://Data.xlsx");
XSSFWorkbook wb= new XSSFWorkbook(fis);
//XSSFSheet sh= wb.getSheetAt(0); Or
XSSFSheet sh = wb.createSheet("Test");
XSSFRow row=sh.createRow(0);
XSSFCell cell= row.createCell(0);
//cell.setCellType(cell.CELL_TYPE_STRING);
cell.setCellValue("Ish Mishra");
FileOutputStream fos=new FileOutputStream("D:\\Data.xlsx");
wb.write(fos);
fos.close();
System.out.println("Excel File Written successfully");