在POI的第一节入门中,我们提供了两个简单的例子,一个是如何用Apache POI新建一个工作薄,另外一个例子是,如果用Apache POI新建一个工作表。那么在这个章节里面,我将会给大家演示一下,如何用Apache POI在已有的Excel文件中插入一行新的数据。具体代码,请看下面的例子。
- importjava.io.File;
- importjava.io.FileInputStream;
- importjava.io.FileNotFoundException;
- importjava.io.FileOutputStream;
- importjava.io.IOException;
- importorg.apache.poi.xssf.usermodel.XSSFCell;
- importorg.apache.poi.xssf.usermodel.XSSFRow;
- importorg.apache.poi.xssf.usermodel.XSSFSheet;
- importorg.apache.poi.xssf.usermodel.XSSFWorkbook;
- publicclassCreatRowTest{
- //当前文件已经存在
- privateStringexcelPath="D:\exceltest\comments.xlsx";
- //从第几行插入进去
- privateintinsertStartPointer=3;
- //在当前工作薄的那个工作表单中插入这行数据
- privateStringsheetName="Sheet1";
- /**
- *总的入口方法
- */
- publicstaticvoidmain(String[]args){
- CreatRowTestcrt=newCreatRowTest();
- crt.insertRows();
- }
- /**
- *在已有的Excel文件中插入一行新的数据的入口方法
- */
- publicvoidinsertRows(){
- XSSFWorkbookwb=returnWorkBookGivenFileHandle();
- XSSFSheetsheet1=wb.getSheet(sheetName);
- XSSFRowrow=createRow(sheet1,insertStartPointer);
- createCell(row);
- saveExcel(wb);
- }
- /**
- *保存工作薄
- *@paramwb
- */
- privatevoidsaveExcel(XSSFWorkbookwb){
- FileOutputStreamfileOut;
- try{
- fileOut=newFileOutputStream(excelPath);
- wb.write(fileOut);
- fileOut.close();
- }catch(FileNotFoundExceptione){
- e.printStackTrace();
- }catch(IOExceptione){
- e.printStackTrace();
- }
- }
- /**
- *创建要出入的行中单元格
- *@paramrow
- *@return
- */
- privateXSSFCellcreateCell(XSSFRowrow){
- XSSFCellcell=row.createCell((short)0);
- cell.setCellValue(999999);
- row.createCell(1).setCellValue(1.2);
- row.createCell(2).setCellValue("Thisisastringcell");
- returncell;
- }
- /**
- *得到一个已有的工作薄的POI对象
- *@return
- */
- privateXSSFWorkbookreturnWorkBookGivenFileHandle(){
- XSSFWorkbookwb=null;
- FileInputStreamfis=null;
- Filef=newFile(excelPath);
- try{
- if(f!=null){
- fis=newFileInputStream(f);
- wb=newXSSFWorkbook(fis);
- }
- }catch(Exceptione){
- returnnull;
- }finally{
- if(fis!=null){
- try{
- fis.close();
- }catch(IOExceptione){
- e.printStackTrace();
- }
- }
- }
- returnwb;
- }
- /**
- *找到需要插入的行数,并新建一个POI的row对象
- *@paramsheet
- *@paramrowIndex
- *@return
- */
- privateXSSFRowcreateRow(XSSFSheetsheet,IntegerrowIndex){
- XSSFRowrow=null;
- if(sheet.getRow(rowIndex)!=null){
- intlastRowNo=sheet.getLastRowNum();
- sheet.shiftRows(rowIndex,lastRowNo,1);
- }
- row=sheet.createRow(rowIndex);
- returnrow;
- }
- }