Packageorg.test;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; Public classPoitesst {//The current file already exists PrivateString Excelpath = "F:\\123abcdefg.xlsx"; //insert in from the first few lines Private intInsertstartpointer = 3; //The work form in the current workbook (Sheet page name) PrivateString sheetname = "Sheet1"; /*** Total Entrance method*/ Public Static voidMain (string[] args) {poitesst CRT=Newpoitesst (); Crt.insertrows (); } /*** Entry method for inserting a new row of data into an existing Excel file*/ Public voidinsertrows () {Xssfworkbook WB=Returnworkbookgivenfilehandle (); Xssfsheet Sheet1=Wb.getsheet (SheetName); Xssfrow Row=CreateRow (Sheet1, Insertstartpointer); Createcell (row); Saveexcel (WB); } /*** Find the number of rows to insert and create a new POI Row Object *@paramsheet *@paramRowIndex *@return */ Privatexssfrow CreateRow (xssfsheet sheet, Integer rowIndex) {xssfrow row=NULL; if(Sheet.getrow (rowIndex)! =NULL) { intLastrowno =Sheet.getlastrownum (); Sheet.shiftrows (RowIndex, Lastrowno,1); } row=Sheet.createrow (RowIndex); returnRow; } /*** Create a row in which to enter the cell *@paramRow *@return */ PrivateXssfcell Createcell (xssfrow row) {Xssfcell cell= Row.createcell (( Short) 0); Cell.setcellvalue (999999); Row.createcell (1). Setcellvalue (1.2); Row.createcell (2). Setcellvalue ("This is a string cell"); returncell; } /*** Save Work Book *@paramWB*/ Private voidSaveexcel (Xssfworkbook wb) {FileOutputStream fileout; Try{fileout=NewFileOutputStream (Excelpath); Wb.write (fileout); Fileout.close (); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } } /*** Get a POI object for an existing workbook *@return */ PrivateXssfworkbook Returnworkbookgivenfilehandle () {Xssfworkbook WB=NULL; FileInputStream FIS=NULL; File F=NewFile (Excelpath); Try { if(F! =NULL) {FIS=NewFileInputStream (f); WB=NewXssfworkbook (FIS); } } Catch(Exception e) {return NULL; } finally { if(FIS! =NULL) { Try{fis.close (); } Catch(IOException e) {e.printstacktrace (); } } } returnWB; } }
Use Apache POI to manipulate Excel files---Insert a new row of data into an existing Excel file