Maven工程POI匯入匯出Excel測試直接可用
阿新 • • 發佈:2019-01-09
1:首先在pom.xml配置匯入jar包
<dependency>
<groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId>
<version>3.5-FINAL</version>
</dependency>
2:複製下面程式碼調整路徑直接測試
/*** 03版讀取
* @throws Exception
*/
@Test
public void testReadExcel() throws Exception
{
//建立輸入流
FileInputStream fis = new FileInputStream(new File("E:\\hello.xls"));
//通過建構函式傳參
HSSFWorkbook workbook = new HSSFWorkbook(fis);
//獲取工作表
HSSFSheet sheet = workbook.getSheetAt(0);
//獲取行,行號作為引數傳遞給getRow方法,第一行從0開始計算
HSSFRow row = sheet.getRow(0);
//獲取單元格,row已經確定了行號,列號作為引數傳遞給getCell,第一列從0開始計算
HSSFCell cell = row.getCell(2);
//設定單元格的值,即C1的值(第一行,第三列)
String cellValue = cell.getStringCellValue();
System.out.println("第一行第三列的值是"+cellValue);
//workbook.close();
fis.close();
}
/**
* 07版讀取
* @throws Exception
*/
@Test
public void read07() throws Exception
{
//建立輸入流
FileInputStream fis = new FileInputStream(new File("E:\\hello.xls"));
//由輸入流得到工作簿
XSSFWorkbook workbook = new XSSFWorkbook(fis);
//得到工作表
XSSFSheet sheet = workbook.getSheet("hello");
//得到行,0表示第一行
XSSFRow row = sheet.getRow(0);
//建立單元格行號由row確定,列號作為引數傳遞給createCell;第一列從0開始計算
XSSFCell cell = row.getCell(2);
//給單元格賦值
String cellValue = cell.getStringCellValue();
System.out.println("C1的值是"+cellValue);
int a[][] = new int[10][30];
for(int i=0;i<a.length;i++)
{
System.out.println(i);
}
// workbook.close();
fis.close();
System.out.println("07讀取");
}
/**
* 通殺版讀取
* @throws Exception
*/
@Test
public void reda03and07() throws Exception
{
//讀取03或07的版本
String filePath = "D:\\hello.xlsx";
if(filePath.matches("^.+\\.(?i)((xls)|(xlsx))$"))
{
FileInputStream fis = new FileInputStream(filePath);
boolean is03Excell = filePath.matches("^.+\\.(?i)(xls)$")?true:false;
Workbook workbook = is03Excell ? new HSSFWorkbook(fis):new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(0);
Cell cell = row.getCell(2);
System.out.println("第一行第一列的資料是:"+cell.getStringCellValue());
System.out.println("03 + 07");
}
}
/**
* 07版寫入 03版也能寫入
* @throws Exception
*/
@Test
public void write07() throws Exception
{
//建立工作簿
XSSFWorkbook workbook = new XSSFWorkbook();
//新建工作表
XSSFSheet sheet = workbook.createSheet("hello");
//建立行,0表示第一行
XSSFRow row = sheet.createRow(0);
//建立單元格行號由row確定,列號作為引數傳遞給createCell;第一列從0開始計算
XSSFCell cell = row.createCell(2);
//給單元格賦值
cell.setCellValue("hello sheet");
//建立輸出流
FileOutputStream fos = new FileOutputStream(new File("E:\\hello.xlsx"));
workbook.write(fos);
// workbook.close();
fos.close();
System.out.println("07寫入");
}