我是Java编码的初学者,想知道如何使用Java阅读以下Excel工作表数据。
另外,我尝试了以下代码 -
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ReadingFromExcelSheet {
public static void main(String[] args) throws EncryptedDocumentException, InvalidFormatException, IOException {
FileInputStream ip = new FileInputStream("C:\\Users\\Sanjana Rajeev\\Desktop\\Murali_YoutubeLinks.xlsx");
Workbook wb = WorkbookFactory.create(ip);
Sheet sheet = wb.getSheet("MySheet1");
int i,j;
int rowcount =3,cellcount=2;
for ( i=0;i<=rowcount;i++){
for (j=0;j<cellcount;j++){
Row row = sheet.getRow(i);
Cell cell = row.getCell(j);
String cellval = cell.getStringCellValue();
System.out.println(cellval + "\t\t" );
}
}
ip.close();
}
}
我得到以下显示的输出:
Topics
YouTube Links
Java Execution
Java and JDK dowload
Eclipse download
Create a Workspace/Project/Package/Class files
https://youtu.be/Pvcv-V69Vc0
Java Execution
Java and JDK dowload
Eclipse download
Create a Workspace/Project/Package/Class files
Datatypes
Variables
String Concatenation
https://youtu.be/Gx0ubuYwTjg
Global Variables (Static & NonStatic)
Local Variables
Memory Allocation
我得到了单元格的值,但没有像excel表那样正确的顺序。有人可以帮忙吗?
答案 0 :(得分:1)
尝试这种方法
public static void main(String[] args) throws EncryptedDocumentException, InvalidFormatException, IOException {
FileInputStream ip = new FileInputStream("C:\\Users\\Sanjana Rajeev\\Desktop\\Murali_YoutubeLinks.xlsx");
Workbook wb = WorkbookFactory.create(ip);
Sheet sheet = wb.getSheet("MySheet1");
Iterator<Row> rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
//iterate over the columns of the current row
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
String cellValue = dataFormatter.formatCellValue(cell);
System.out.print(cellValue + "\t");
}
//append empty line
System.out.println();
}
ip.close();
}
答案 1 :(得分:0)
这会改善格式吗?
for ( i=0;i<=rowcount;i++)
{
Row row = sheet.getRow(i);
for (j=0;j<cellcount;j++)
{
Cell cell = row.getCell(j);
String cellval = cell.getStringCellValue();
System.out.print(cellval + "\t\t" );
}
System.out.println();
}