这是我正在做的事情的要点。
我正在创建一个 ExcelProcessor 对象,然后该对象将获取我在构造函数中指定的文件。在此之后,我检索书籍、行,然后是行中的单元格。第一行具有每列保存数据的名称。不幸的是,如果任何单元格连续为空白,它就会立即停止处理。有没有办法说在每行中读取 X 列?
谢谢!
public class ExcelProcessor
{
private static File xslFile;
ExcelProcessor( String file )
{
xslFile = new File(file);
}
/**
* creates an {@link HSSFWorkbook} the specified OS filename.
*/
/**
* Returns an XSSF Workbook object that can be queried.
*
* This method either returns a Workbook with the specified
* file location or it will throw an IO Error.
*
* @return the Excel Workbook
* @see XSSFWB
*/
private XSSFWorkbook readFile() throws IOException
{
return new XSSFWorkbook(new FileInputStream(xslFile));
}
/**
* Returns all rows of the XSSF Workbook that is read in via the file system.
*
* This method returns a XSSFRow array for processing
*
* @param wb the Excel workbook located on the file system
* @return Rows contained within the Excel Workbook
* @see XSSFRows
*/
private XSSFRow[] retrieveRows(XSSFWorkbook wb)
{
XSSFSheet xslSheet = wb.getSheetAt(0);
XSSFRow[] sheetRows = new XSSFRow[xslSheet.getLastRowNum()];
for (int i = 0; i < xslSheet.getLastRowNum(); i++)
{
sheetRows[i] = xslSheet.getRow(i);
}
return sheetRows;
}
private XSSFWorkbook modifyRows(XSSFWorkbook wb)
{
return wb;
}
/**
* Processes all rows of the XSSF Workbook that is read in via the file system.
* Each Cell is pulled from the rows to create a structure needed for WQS
* Web Services.
*
* This method returns a String array for all Cells pulled from the Rows
*
* @param xslRow Current row pulled from the XSL Workbook
* @return String Array of all Row Cell Values
* @see String[]
*/
public String[] processRow(XSSFRow xslRow)
{
int totalCells = xslRow.getPhysicalNumberOfCells();
System.out.println("Total Cells: " + totalCells);
String[] cellValues = new String[totalCells];
for (int i = 0; i < totalCells; i++)
{
XSSFCell currentCell = xslRow.getCell(i);
String cellVal;
try
{
cellVal = currentCell.getStringCellValue();
}
catch (Exception e)
{
System.out.println("Empty Cell");
cellVal = "";
}
cellValues[i] = cellVal;
System.out.println(cellVal);
}
return cellValues;
}
/**
* Main method which creates an ExcelProcessor before handling the Excel
* Spreadsheet given to the user.
*
* @param args
* @throws ParserConfigurationException
* @throws SAXException
*/
public static void main(String args[]) throws ParserConfigurationException, SAXException
{
ExcelProcessor driver = new ExcelProcessor("D:\\TestBook.xlsx");
try
{
XSSFWorkbook xslWB = driver.readFile();
XSSFRow[] xslRows = driver.retrieveRows(xslWB);
ArrayList<String[]> rowCellVals = new ArrayList<String[]>();
for (int r = 0; r < xslRows.length; r++)
{
rowCellVals.add(driver.processRow(xslRows[r]));
}
String sessionKey = WQSServices.sessionToken();
System.out.println("Have the Session Key: " + sessionKey);
WQSServices.uploadAttachment(sessionKey, rowCellVals);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}