使用Apache POI 3.16 Eclipse IDE霓虹灯3 Selenium 3.4(在这种情况下不重要)
我遇到了将值写入excel电子表格然后读回值的问题。
这是我想要在高层做的事情:
单元格包含值“B2”。在setCellData()函数中,我向单元格写入“Hello World”并让函数返回单元格的内容。我还有一个单独的函数,它读入指定单元格的内容。
当我运行以下代码时:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Udemy_Excel_Driven {
public static XSSFWorkbook wb;
public static XSSFSheet sheet;
public static XSSFRow row;
public static XSSFCell cell;
public static FileInputStream fis;
public static void main(String[] args) throws IOException, Exception
{
System.out.println("Before cell edit value is:");
System.out.println(getCellData(1,1));
String value = setCellData(1,1,"Hello World");
System.out.println("What's the value after setting it with setCellData()?");
System.out.println(value);
System.out.println("What's the value using getCellData()?");
System.out.println(getCellData(1,1));
}
public static String getCellData(int rowNum, int colNum) throws IOException
{
/*
* Hierarchy of excel data:
*
* Workbook - take control of this
* Sheet - pick up the sheet of the workbook
* Row - pick the row
* Column - after picking the row, select the column
* Value - grab the value from the cell
*
*/
//0. = identify the path to the excel file in the system.
fis = new FileInputStream("C:\\data.xlsx");
//1. Create a new XSSFWorkbook object. You need to pass in a FileInputStream object into it, which you created earlier.
wb = new XSSFWorkbook(fis);
//2. Get the sheet in the workbook. Create a new XSSFsheet object and set it to the sheet in the workbook
// Access the workbook method "getSheet" and pass in the name of the sheet
sheet = wb.getSheet("script");
//3. Get the row and column. We are going to access the data from row 2 column 2. And remember the indices start at 0.
row = sheet.getRow(rowNum);
cell = row.getCell(colNum);
//get the value specified in the row and cell
return cell.getStringCellValue();
}
public static String setCellData(int rowNum, int colNum, String data) throws IOException
{
fis = new FileInputStream("C:\\data.xlsx");
wb = new XSSFWorkbook(fis);
sheet = wb.getSheet("script");
row = sheet.getRow(rowNum);
cell = row.getCell(colNum);
cell.setCellValue(data);
String cellData = cell.getStringCellValue();
return cellData;
}
我得到以下输出:
Before cell edit value is:
B2
What's the value after setting it with setCellData()?
Hello World
What's the value using getCellData()?
B2
我认为自从我打开excel文件并且“Hello World”字符串不在指定的单元格中时,实际上没有发生写入。这个问题的答案是什么?
答案 0 :(得分:1)
我没有看到您的代码中有任何部分实际写入您的文件。 它应该或多或少看起来像这样:
FileOutputStream fileOut = new FileOutputStream("C:\\data.xlsx");
wb.write(fileOut);
fileOut.close();
您也可以参考此guide来解决此问题以及您可能有兴趣实施的其他功能。