In the first section of the POI, we provide two simple examples of how to create a new workbook with Apache Poi, and another example is to create a new worksheet with Apache POI. So in this section, I'll show you how to insert a new row of data into an existing Excel file using Apache poi. For specific code, see the example below.
Import Java.io.file;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Org.apache.poi.xssf.usermodel.xssfcell;import Org.apache.poi.xssf.usermodel.xssfrow;import Org.apache.poi.xssf.usermodel.xssfsheet;import Org.apache.poi.xssf.usermodel.xssfworkbook;public class Creatrowtest {//The current file already exists private String Excelpath = "d:\\ Exceltest\\comments.xlsx ";//Insert in the first few lines private int insertstartpointer = 3;//Insert this row of data in the worksheet of the current workbook private String SheetName = "Sheet1";/** * Total ingress method */public static void Main (string[] args) {creatrowtest crt = new Creatrowtest (); crt.inse Rtrows ();} /** * Entry method for inserting a new row of data into an existing Excel file */public void InsertRows () {Xssfworkbook wb = Returnworkbookgivenfilehandle (); Xssfsheet Sheet1 = Wb.getsheet (sheetname); Xssfrow row = CreateRow (Sheet1, Insertstartpointer); Createcell (row); Saveexcel (WB);} /** * Save Workbook * @param wb */private void Saveexcel (Xssfworkbook wb) {FileOutputStream Fileout;try {fileout = new FileOutputStream (Excelpath); Wb.write (fileout); Fileout.close ();} catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ()}} /** * Create rows to be in and out of cells * @param row * @return */private Xssfcell Createcell (xssfrow row) {Xssfcell cell = row.c Reatecell ((short) 0); Cell.setcellvalue (999999); Row.createcell (1). Setcellvalue (1.2); Row.createcell (2). Setcellvalue ("This is a string cell"); return cell;} /** * Get the POI object of an existing workbook * @return */private xssfworkbook returnworkbookgivenfilehandle () {Xssfworkbook WB = null;f Ileinputstream FIS = null; File F = new file (Excelpath), try {if (f! = null) {FIS = new FileInputStream (f); wb = new Xssfworkbook (FIS);}} catch (Except Ion e) {return null;} finally {if (FIS! = null) {try {fis.close ();} catch (IOException e) {e.printstacktrace ()}}} return WB;} /** * Find the number of rows to insert and create a new POI Row Object * @param sheet * @param rowIndex * @return */private xssfrow createrow (XSSFS Heet sheet, Integer rowIndex{Xssfrow row = null;if (Sheet.getrow (rowIndex)! = null) {int lastrowno = Sheet.getlastrownum (); Sheet.shiftrows (RowIndex , Lastrowno, 1);} row = Sheet.createrow (rowIndex); return row;}}
(2) How to manipulate Excel files with Apache POI-----How do I insert a new row of data into an existing Excel file?