項(xiàng)目第四天beforeclass課前首先從Workbook開始我們的POI編程之旅要生成一個(gè)_第1頁(yè)
項(xiàng)目第四天beforeclass課前首先從Workbook開始我們的POI編程之旅要生成一個(gè)_第2頁(yè)
項(xiàng)目第四天beforeclass課前首先從Workbook開始我們的POI編程之旅要生成一個(gè)_第3頁(yè)
項(xiàng)目第四天beforeclass課前首先從Workbook開始我們的POI編程之旅要生成一個(gè)_第4頁(yè)
項(xiàng)目第四天beforeclass課前首先從Workbook開始我們的POI編程之旅要生成一個(gè)_第5頁(yè)
已閱讀5頁(yè),還剩89頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

HSSFWorkbook(創(chuàng)建excel首先從Workbook們的POIWorkbook,需要用到HSSFWorkbookpublicclassHSSFWorkbookextendsCreatesnewHSSFWorkbookfromscratch(starthere!)HSSFWorkbook(java.io.InputStreams)HSSFWorkbook(java.io.InputStreams,booleanpreserveNodes)CompaniontoHSSFWorkbook(POIFSFileSystem),thisconstructsthePOIfilesystemaroundyourHSSFWorkbook(POIFSFileSystemfs)HSSFWorkbook(POIFSFileSystemfs,booleanpreserveNodes)givenaPOIPOIFSFileSystemobject,readinitsWorkbookandpopulatethehighandlowlevel我們用第一個(gè)構(gòu)建器來(lái)生成一個(gè)WorkbookpublicCreatesnewHSSFWorkbookfromscratch(startHSSFWorkbookworkbook=new接下來(lái)再來(lái)對(duì)生成的Workbook「HSSFWorkbook」類的「write」方法:publicvoidwrite(java.io.OutputStreamstream)throwsMethodwrite-writeoutthisworkbooktoanOutputstream.ConstructsanewPOIPOIFSFileSystem,passesintheworkbookbinaryrepresentationandwritesitout.stream--thejavaOutputStreamyouwishtowritetheXLStojava.io.IOException-ifanythingcan'tbeimportimportpublicclasspublicstaticvoidmain(String[]HSSFWorkbookworkbooknewHSSFWorkbook();//創(chuàng)建一個(gè)空白的FileOutputStreamout=null;out=newworkbook.write(out);//調(diào)用HSSFWorkbookwrite法}catch(IOExceptione){try{}catch(IOExceptione){}}}}POIFSFileSystem類(excel表格這次我們用POI在的Workbook。因?yàn)闆](méi)有現(xiàn)成的方法,所以只能再次利用HSSFWorkbook方publicHSSFWorkbook(POIFSFileSystemfs)throws-POIFSFileSystempublicclassPOIFSFileSystemextendsjava.lang.ObjectimplementsConstructor,intendedforPOIFSFileSystem(java.io.InputStreamCreateaPOIFSFileSystemfromanpublicPOIFSFileSystem(java.io.InputStreamstream)throwsCreateaPOIFSFileSystemfromanstream-theInputStreamfromwhichtoreadthedatajava.io.IOException-onerrorsreading,oroninvalid參數(shù)設(shè)定為讀入Excel「InputStreamFileInputStreamin=newFileInputStream("sample.xls");//文件輸入流POIFSFileSystemfsnewPOIFSFileSystem(in)poifsfileSystemHSSFWorkbookwb=newHSSFWorkbook(fs);通過(guò)POIFSFileSystemExcel文件下面就實(shí)際做一下如何Excel文件。importimportorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.poifs.filesystem.POIFSFileSystem;publicclasspublicstaticvoidmain(String[]args){FileInputStreamin=null;HSSFWorkbookworkbook=null;innewFileInputStream("sample1.xls");//將excel件轉(zhuǎn)為輸入POIFSFileSystemfsnewPOIFSFileSystem(in);//構(gòu)建POIFSFileSystem構(gòu)workbooknewHSSFWorkbook(fs);//創(chuàng)建個(gè)workbook,根據(jù)POIFSFileSystem}catch(IOExceptione){}catch(IOExceptione){}}FileOutputStreamout=null;out=newFileOutputStream("sample2.xls");}catch(IOExceptione){try{}catch(IOExceptione){}}}}關(guān)于publicclassHSSFSheetextendsprotectedHSSFSheet(WorkbookCreatesnewHSSFSheet–calledbyHSSFWtectedHSSFSheet(Workbookbook,Sheetsheet)CreatesanHSSFSheetrepresentingthegivenSheet雖然有兩個(gè)構(gòu)建器,但都是protected新建Sheet,只能通過(guò)Workbook。SheetWorkbook新建SheetHSSFWorkbook」類的「createSheet」的方法,詳細(xì)可以參照「在Workbook創(chuàng)Sheet」。HSSFWorkbookworkbooknewHSSFWorkbook();//創(chuàng)建個(gè)空白的workbookHSSFSheetsheet=workbook.createSheet()sheet現(xiàn)有的對(duì)于在Workbook已經(jīng)存在的Sheet來(lái)說(shuō),可以用「HSSFWorkbook」類的「getSheet」方法來(lái)publicHSSFSheetgetSheet(java.lang.Stringname)Getsheetwiththegivennamename-ofthesheetHSSFSheetwiththenameprovidedornullifitdoesnot(java.lang.Stringname)參數(shù)為SheetHSSFWorkbookworkbook=newHSSFSheetsheet=workbook.getSheet("sheet1")//名稱為sheet1的publicHSSFSheetgetSheetAt(intGettheHSSFSheetobjectatthegivenindex-ofthesheetnumber(0-basedphysical&logical)HSSFSheetattheprovidedindex(intindex)參數(shù)為sheet序號(hào)HSSFWorkbookworkbook=newHSSFSheetsheet=workbook.getSheetAt(1);//序號(hào)為1的sheet(第二張Workbook要在Workbook建一個(gè)Sheet,可以使用「HSSFWorkbook」類的「createSheet」方法。publicHSSFSheetcreateanHSSFSheetforthisHSSFWorkbook,addsittothesheetsandreturnsthehighlevelrepresentation.UsethistocreatenewHSSFSheetrepresentingthenewpublicHSSFSheetcreateSheet(java.lang.StringcreateanHSSFSheetforthisHSSFWorkbook,addsittothesheetsandreturnsthehighlevelrepresentation.Usethistocreatenewsheetname-sheetnametosetforthesheet.HSSFSheetrepresentingthenewsheet.創(chuàng)建的Sheet「HSSFSheet」類對(duì)象返回。importimportpublicclasspublicstaticvoidmain(String[]args){HSSFWorkbookworkbook=newHSSFWorkbook();workbook.createSheet();//創(chuàng)建workbooksheetFileOutputStreamout=null;out=newFileOutputStream("sample.xls");}catch(IOExceptione){try{}catch(IOExceptione){}}}}如果沒(méi)有設(shè)定Sheet會(huì)從0設(shè)定為Sheet0,Sheet1,設(shè)定為test以創(chuàng)建testSheetWorkbook要Workbook里現(xiàn)有的Sheet來(lái)創(chuàng)建新的Sheet,可以使用「HSSFWorkbook」類的「cloneSheet」方法。publicHSSFSheetcloneSheet(intcreateanHSSFSheetfromanexistingsheetintheHSSFSheetrepresentingthecloned指定要的Sheet序列號(hào)。 前Workbook如下importimportorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.poifs.filesystem.POIFSFileSystem;publicclasspublicstaticvoidmain(String[]args){FileInputStreamin=null;HSSFWorkbookworkbook=null;in=newFileInputStream("sample.xls");POIFSFileSystemfs=newPOIFSFileSystem(in);workbook=newHSSFWorkbook(fs);}catch(IOExceptione){}catch(IOExceptione){}}FileOutputStreamout=out=newFileOutputStream("sample.xls");}catch(IOExceptione){try{}catch(IOExceptione){}}}}可以看出,兩個(gè)Sheet被成功。被的Sheet名格式是「原Sheet名(序列號(hào))」。順便一提的是,如果你手動(dòng)在Excel里進(jìn)行復(fù)制的話,被的Sheet名的格式是「原Sheet名(序列號(hào))」。也就是原Sheet名和(序列號(hào))之間有一個(gè)半角空格。Workbook要從Workbook刪除Sheet,可以使用「HSSFWorkbook」類的方法「removeSheetAt」。publicvoidremoveSheetAt(intindex)removessheetatthegivenindexindex-ofthesheet(0-(intindex)指定要?jiǎng)h除Sheet號(hào)publicintgetSheetIndex(java.lang.Stringname)Returnstheindexofthesheetbyhisnamename-thesheetnameindexofthesheet(0(java.lang.Stringname)參數(shù)請(qǐng)指定要?jiǎng)h除的Sheetimportimportpublicclasspublicstaticvoidmain(String[]args){HSSFWorkbookworkbook=newHSSFWorkbook();System.out.println("Sheet0="+workbook.getSheetIndex("Sheet0"));System.out.println("Sheet2="+FileOutputStreamout=null;out=newFileOutputStream("sample.xls");}catch(IOExceptione){try}catch(IOExceptione){}}}}「getSheetIndex」,設(shè)定Sheet看Sheet0=Sheet2=我們發(fā)現(xiàn)中間的Sheet面的Sheet往前移一個(gè),總之會(huì)維持從0要改變現(xiàn)有Sheet新建Sheet「HSSFWorkbook」類的「setSheetName」方法publicvoidsetSheetName(intsheet,java.lang.Stringsetthesheetname.WillthrowIllegalArgumentExceptionifthenameisgreaterthan31charsorcontains/\?*[]sheet-number(0參數(shù):(intsheet)指定要改變的Sheet(java.lang.Stringname)為要改變的名稱,設(shè)置名稱時(shí),最大長(zhǎng)度是指定漢字SheetpublicvoidsetSheetName(intsheet,java.lang.Stringshort-static staticbyte 參數(shù)(intsheet,java.lang.Stringname,shortencoding)intsheet sheet號(hào)java.lang.String shortencoding importimportpublicclasspublicstaticvoidmain(String[]args){HSSFWorkbookworkbook=newHSSFWorkbook();workbook.setSheetName(0,"test")sheet0名字為workbook.setSheetName(1,試HSSFWorkbook.ENCODING_UTF_16);//更改sheet1置為utf-FileOutputStreamout=null;out=newFileOutputStream("sample.xls");}catch(IOExceptione){try{}catch(IOExceptione){}}}}可以看出,漢字Sheet了使用「createSheet」方法創(chuàng)建新的SheetencodingSheet能先新建一個(gè)Sheet,然后再對(duì)該SheetpublicvoidsetColumnWidth(shortcolumn,shortwidth)setthewidth(inunitsof1/256thofacharacterwidth)column--thecolumntoset(0-width--thewidthinunitsof1/256thofacharacter(shortcolumn)指定列的序列號(hào)(shortwidth)指定列的寬度。寬度如果指定1字的1/256(也就是說(shuō)一個(gè)文字占256),41024。publicshortgetColumnWidth(shortgetthewidth(inunitsof1/256thofacharacterwidthcolumn--thecolumntoset(0-based)width-thewidthinunitsof1/256thofacharacter(shortcolumn)指定列的序列號(hào)自己動(dòng)手做一下吧。仍然按照下圖準(zhǔn)備一個(gè)Excel取得從第0到第2把第2定給第0和第1importimportorg.apache.poi.poifs.filesystem.POIFSFileSystem;importorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.hssf.usermodel.HSSFSheet;publicclasspublicstaticvoidmain(String[]args){FileInputStreamin=null;HSSFWorkbookworkbook=null;in=newFileInputStream("sample.xls");POIFSFileSystemfs=newPOIFSFileSystem(in);workbook=newHSSFWorkbook(fs);}catch(IOExceptione){}catch(IOExceptione){}}HSSFSheetsheet=workbook.getSheetAt(0);short[]width=newshort[3];for(inti=0;i<3;width[i]=sheet.getColumnWidth((short)i);System.out.println(iwidth[i]);}//循環(huán)獲取0,1,2//將第二列的寬度賦給第0,1sheet.setColumnWidth((short)0width[2]);sheet.setColumnWidth((short)1FileOutputStreamout=null;out=newFileOutputStream("sample2.xls");}catch(IOExceptione){try{}catch(IOException}}}}0寬1寬2寬一個(gè)Excel們也可以用POIpublicvoidsetDefaultColumnWidth(shortsetthedefaultcolumnwidthforthesheet(ifthecolumnsdonotdefinetheirownwidth)incharacterswidth-defaultcolumnpublicshortgetthedefaultcolumnwidthforthesheet(ifthecolumnsdonotdefinetheirownwidth)incharactersdefaultcolumnimportimportorg.apache.poi.poifs.filesystem.POIFSFileSystem;importorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.hssf.usermodel.HSSFSheet;publicclasspublicstaticvoidmain(String[]args){HSSFWorkbookworkbook=newHSSFWorkbook();HSSFSheetsheet=workbook.createSheet();FileOutputStreamout=null;out=newFileOutputStream("sample2.xls");}catch(IOExceptione){try{}catch(IOExceptione){}}}}Sheet有時(shí)我們可能會(huì)手動(dòng)去調(diào)整工作表Sheet例,用POI「HSSFSheet」類的「setZoom」方publicvoidsetZoom(intnumerator,intSetsthezoommagnicationforthesheet.Thezoomisexpressedasafraction.Forexampletoexpressazoomof75%use3forthenumeratorand4forthedenominator.numerator-Thenumeratorforthezoommagnification.denominator-Thedenominatorforthezoommagnification.(intnumerator,intdenominator)參數(shù),這樣就可以指定顯示比例了,指定方法是用”numerator”÷”denominator”,比方說(shuō)「setZoom(2,1)」就是設(shè)定為200%的比例,「setZoom(34)」就是設(shè)定為75%的比例。importimportorg.apache.poi.poifs.filesystem.POIFSFileSystem;importorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.hssf.usermodel.HSSFSheet;importpublicclasspublicstaticvoidmain(String[]args){FileInputStreamin=null;HSSFWorkbookworkbook=null;in=newFileInputStream("sample.xls");POIFSFileSystemfs=newPOIFSFileSystem(in);workbook=newHSSFWorkbook(fs);}catch(IOExceptione){}catch(IOExceptione){}}HSSFSheetsheetworkbook.getSheetAt(0);//取得序號(hào)為0sheetsheet.setZoom(2,1);//改變sheet例為200%FileOutputStreamout=null;out=newFileOutputStream("sample2.xls");}catch(IOExceptione){try{}catch(IOExceptione){}}}}publicintaddMergedRegion(Regionaddsamergedregionofcells(hencethosecellsformregion-(rowfrom/colfrom-rowto/colto)tomergeindexofthispublicclassRegionextendsjava.lang.Object publicRegion(introwFrom,shortcolFrom,introwTo,shortcolTorowFromcolFromrowTo-Region(1,(short)1,2,動(dòng)手做做看,還是使用原來(lái)的Excelimportimportorg.apache.poi.poifs.filesystem.POIFSFileSystem;importorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.hssf.usermodel.HSSFSheet;importpublicclasspublicstaticvoidmain(String[]args){FileInputStreamin=null;HSSFWorkbookworkbook=null;in=newFileInputStream("sample.xls");POIFSFileSystemfs=newPOIFSFileSystem(in);workbook=newHSSFWorkbook(fs);}catch(IOExceptione){}catch(IOExceptione){}}HSSFSheetsheet=sheet.addMergedRegion(newRegion(1,(short)1,2,short)3));//從第2第2到第3第4FileOutputStreamout=null;out=newFileOutputStream("sample2.xls");}catch(IOExceptione){try{}catch(IOExceptione){}}}}把剛作成的新的ExcelHSSFRowpublicclassHSSFRowextendsjava.lang.Object 構(gòu)造方protectedprotectedHSSFRow(Workbookbook,Sheetsheet,introwNum)CreatesnewHSSFRowfromtectedHSSFRow(Workbookbook,Sheetsheet,RowRecordrecord)CreatesanHSSFRowfromalowlevelRowRecordobject.雖然有三個(gè),但每一個(gè)都是protected使用它的構(gòu)造方法,而是用SheetHSSFWorkbookworkbook=newHSSFWorkbook();HSSFSheetsheet=workbook.createSheet();HSSFRowrow=sheet.createRow(0);在工作表里取得行,使用「HSSFSheet」類的「getRow」方法,詳細(xì)內(nèi)容你可以參照一下『Sheet里行的』。HSSFWorkbookworkbook=newHSSFWorkbook();HSSFSheetsheet=workbook.createSheet();HSSFRowrow=sheet.getRow(0);publicintgetFirstRowNum()getsthefirstrowonthesheetthenumberofthefirstlogicalrowonthepublicintgetLastRowNum()getsthelastrowonthesheetlastrowcontainednthispublicintReturnsthenumberofphsyicallydefinedrows(NOTthenumberofrowsinthesheet)importorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.hssf.usermodel.HSSFSheet;importorg.apache.poi.hssf.usermodel.HSSFRow;publicclasspublicstaticvoidmain(String[]args){HSSFWorkbookworkbook=newHSSFWorkbook();HSSFSheetsheet=workbook.createSheet();System.out.println("First:"+sheet.getFirstRowNum());//sheet.getFirstRowNum()獲取sheetSystem.out.println("Last:"+sheet.getLastRowNum());//getLastRowNum()獲取sheet行號(hào)System.out.println("Totalsheet.getPhysicalNumberOfRowsngetPhysicalNumberOfRows()獲取sheet數(shù)System.out.println("Firstsheet.getFirstRowNum());System.out.println("Last:"+sheet.getLastRowNum());System.out.println("Total:"+sheet.getPhysicalNumberOfRows()+"\n");System.out.println("First:"+sheet.getFirstRowNum());System.out.println("Last:"+sheet.getLastRowNum());System.out.println("Totalsheet.getPhysicalNumberOfRows());}}getPhysicalNumberOfRows()在的行之前僅僅新建了Sheet,雖然可以看到新建的Sheet格,但還不能直接往這些單元格設(shè)值。要想往這些單元格里設(shè)值,你還publicHSSFRowcreateRow(intCreateanewrowwithinthesheetandreturnthehighlevelrepresentationrownum-rownumberHighlevelHSSFRowobjectrepresentingarowinthe(intrownum)創(chuàng)建指定行號(hào)的行。行號(hào)是從0最大是65535,可以支持65536返回的值是「HSSFRow」類對(duì)創(chuàng)建方法很多,要說(shuō)詳細(xì)挺復(fù)雜。比方說(shuō),即使第一行(行號(hào)0)和第二行不創(chuàng)建,也能直接創(chuàng)建第三行。importimportorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.hssf.usermodel.HSSFSheet;importorg.apache.poi.hssf.usermodel.HSSFRow;importorg.apache.poi.hssf.usermodel.HSSFCell;publicclasspublicstaticvoidmain(String[]HSSFWorkbookworkbook=newHSSFWorkbook();//創(chuàng)建個(gè)空白的workbookHSSFSheetsheet=workbook.createSheet();//創(chuàng)建個(gè)空白的sheetHSSFRowrowsheet.createRow(2);//創(chuàng)建行號(hào)為2行,excelHSSFCellcellrow.createCell((short)0);//創(chuàng)建上面行的第一個(gè)單元格cell.setCellValue("test");//將test元格FileOutputStreamout=null;out=newFileOutputStream("sample.xls");}catch(IOExceptione){try{}catch(IOExceptione){}}}}在上面的程序里,生成一個(gè)Sheet,然后單獨(dú)創(chuàng)建了第三行(行號(hào)為2),接著又創(chuàng)建了一個(gè)單元格,最后給這個(gè)單元格設(shè)了值。執(zhí)行行要取得Sheet「HSSFSheet」類的「getRowpublicHSSFRowgetRow(intReturnsthelogicalrow(notphysical)0-based.Ifyouaskforarowthatisnotdefinedyougetanull.Thisistosayrow4representsthefifthrowonasheet.rownum-rowtogetHSSFRowrepresentingtherownumberornullifitsnotdefinedontheimportimportorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.hssf.usermodel.HSSFSheet;importorg.apache.poi.hssf.usermodel.HSSFRow;publicclasspublicstaticvoidmain(String[]args){HSSFWorkbookworkbook=newHSSFWorkbook();HSSFSheetsheet=workbook.createSheet();HSSFRowrow=sheet.createRow(1);for(inti=0;i<3;i++){HSSFRowr=sheet.getRow(i);if(r==null){System.out.println("第iSystem.out.println("第i。}}}}1功2importimportorg.apache.poi.poifs.filesystem.POIFSFileSystem;importorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.hssf.usermodel.HSSFSheet;importpublicclasspublicstaticvoidmain(String[]args){FileInputStreamin=null;HSSFWorkbookworkbook=null;in=newFileInputStream("sample.xls");POIFSFileSystemfs=newPOIFSFileSystem(in);workbook=newHSSFWorkbook(fs);}catch(IOExceptione){}catch(IOExceptione){}}HSSFSheetsheet=workbook.getSheetAt(0);//序號(hào)為0的sheetfor(inti=0;i<3;i++){HSSFRowr=sheet.getRow(i);if(r==null){System.out.println("第iSystem.out.println("第i。}}}}0功1功這一次從已經(jīng)取得的行里獲取單元格的值。仍然使用剛才的ExcelgetRowimportimportorg.apache.poi.poifs.filesystem.POIFSFileSystem;importorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.hssf.usermodel.HSSFSheet;importorg.apache.poi.hssf.usermodel.HSSFRow;importorg.apache.poi.hssf.usermodel.HSSFCell;publicclasspublicstaticvoidmain(String[]args){FileInputStreamin=null;HSSFWorkbookworkbook=null;in=newFileInputStream("sample.xls");POIFSFileSystemfs=newPOIFSFileSystem(in);workbook=newHSSFWorkbook(fs);}catch(IOExceptione){}catch(IOExceptione){}}HSSFSheetsheet=workbook.getSheetAt(0);//序號(hào)為0的sheetHSSFRowrow=sheet.getRow(1);//取得sheet二行(行號(hào)1)HSSFCellcell=row.getCell((short)1);//取得第二行,第二格(單元格號(hào)1)}}最后,再來(lái)試試看,在現(xiàn)有的行上,用「createRow」方法創(chuàng)建一行看看會(huì)是什么結(jié)果。還是使用剛才的Excel在第二行上創(chuàng)建一importimportorg.apache.poi.poifs.filesystem.POIFSFileSystem;importorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.hssf.usermodel.HSSFSheet;importorg.apache.poi.hssf.usermodel.HSSFRow;importorg.apache.poi.hssf.usermodel.HSSFCell;publicclasspublicstaticvoidmain(String[]args){FileInputStreamin=null;HSSFWorkbookworkbook=null;in=newFileInputStream("sample.xls");POIFSFileSystemfs=newPOIFSFileSystem(in);workbook=newHSSFWorkbook(fs);}catch(IOExceptione){}catch(IOExceptione){}}HSSFSheetsheetworkbook.getSheetAt(0)HSSFRowrowsheet.createRow(1);//在已經(jīng)有第二行的情況下再建第二行HSSFCellcell=row.getCell((short)1);//取得新建第二行的值}}Exceptioninthread"main"java.lang.NullPointerExceptionatPOISample.main(POISample.java:35)發(fā)生了空指針異常。本來(lái)對(duì)于已經(jīng)存在的行用「createRow」方法進(jìn)行創(chuàng)建行操作,可能你會(huì)以為會(huì)原來(lái)的行,但事實(shí)并非如此。importimportorg.apache.poi.poifs.filesystem.POIFSFileSystem;importorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.hssf.usermodel.HSSFSheet;importorg.apache.poi.hssf.usermodel.HSSFRow;importorg.apache.poi.hssf.usermodel.HSSFCell;publicclasspublicstaticvoidmain(String[]args){FileInputStreamin=null;HSSFWorkbookworkbook=null;in=newFileInputStream("sample.xls");POIFSFileSystemfs=newPOIFSFileSystem(in);workbook=newHSSFWorkbook(fs);}catch(IOExceptione){}catch(IOExceptione){}}HSSFSheetsheet=HSSFRowrow=HSSFCellcell=row.createCell((short)3);FileOutputStreamout=null;out=newFileOutputStream("sample2.xls");}catch(IOExceptione){try{}catch(IOExceptione){}}}}publicvoidshiftRows(intstartRow,intendRow,intShiftsrowsbetweenstartRowandendRownnumberofrows.Ifyouanegativenumber,itwillshiftrowsup.Codeensuresthatrowsdon'twraparound.CallsshiftRows(startRow,endRow,n,false,false);Additionallyshiftsmergedregionsthatarecompleydefinedintheserows(ie.merged2cellsonarowtobeshifted).startRow-therowtostartshiftingendRow-therowtoendshiftingn-thenumberofrowstointstartRow,intendRow:指定要移動(dòng)的行的范圍從「startRow」行到「endRow」行。intn:「n」如果是正數(shù)就往下移動(dòng)的行數(shù),如果為負(fù),就往上移動(dòng)。按下圖準(zhǔn)備一個(gè)Excelimportimportorg.apache.poi.poifs.filesystem.POIFSFileSystem;importorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.hssf.usermodel.HSSFSheet;importpublicclasspublicstaticvoidmain(String[]args){FileInputStreamin=null;HSSFWorkbookworkbook=null;in=newFileInputStream("sample.xls");POIFSFileSystemfs=newPOIFSFileSystem(in);workbook=newHSSFWorkbook(fs);}catch(IOExceptione){}catch(IOException}}HSSFSheetsheet=sheet.shiftRows(12,2);//第二行和第三行向下移動(dòng)兩行FileOutputStreamout=null;out=newFileOutputStream("sample2.xls");}catch(IOExceptione){try{}catch(IOExceptione){}}}}打開新建的Sample2.xls看publicvoidshiftRows(intstartRow,intendRow,intbooleancopyRowHeight,booleanShiftsrowsbetweenstartRowandendRownnumberofrows.Ifyouanegativenumber,itwillshiftrowsup.Codeensuresthatrowsdon'twraparoundAdditionallyshiftsmergedregionsthatarecompleydefinedintheserows(ie.merged2cellsonarowtobeshifted).TODOMightwanttoaddboundscheckingstartRow-therowtostartshiftingendRow-therowtoendshiftingn-thenumberofrowstocopyRowHeight-whethertocopytherowheightduringtheshiftresetOriginalRowHeight-whethertosettheoriginalrow'sheighttotheimportimportorg.apache.poi.poifs.filesystem.POIFSFileSystem;importorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.hssf.usermodel.HSSFSheet;importpublicclasspublicstaticvoidmain(String[]args){FileInputStreamin=null;HSSFWorkbookworkbook=null;in=newFileInputStream("sample.xls");POIFSFileSystemfs=newPOIFSFileSystem(in);workbook=newHSSFWorkbook(fs);}catch(IOExceptione){}catch(IOException}}HSSFSheetsheet=sheet.shiftRows(12,2,truetrue);//第二行和第三行保留原來(lái)高度向下移動(dòng)兩行,原欄位恢復(fù)默認(rèn)高度FileOutputStreamout=null;out=newFileOutputStream("sample2.xls");}catch(IOExceptione){try{}catch(IOExceptione){}}}}再打開新生成的Sample2.xlsHSSFCellpublicclassHSSFCellextendsprotectedHSSFCell(Workbookbook,Sheetsheet,introw,CellValueRecordInterfacecval)CreatesanHSSFCellfromaCellValueRecordItectedHSSFCell(Workbookbook,Sheetsheet,introw,shortcol)CreatesnewCell–ShouldonlybecalledbyHSSFRtectedHSSFCell(Workbookbook,Sheetsheet,introw,shortcol,inttype)Deprecated.Asof22-Jan-2002use@seeorg.apache.poi.hssf.usermodel.HSSFRow#createCell(short)andusesetCellValuetospecifythetypelazily.同之前一樣,雖然有三個(gè)構(gòu)造方法,但都是protected型的,所以直接用構(gòu)造方法創(chuàng)建單元格行不通,只能通過(guò)行來(lái)創(chuàng)建單元格。HSSFWorkbookworkbook=newHSSFWorkbook();HSSFSheetsheet=workbook.createSheet();HSSFRowrow=sheet.createRow(0);HSSFCellcell=要某一行現(xiàn)有的單元格,使用「HSSFRow」類的「getCell」方法,詳細(xì)請(qǐng)參照『?jiǎn)卧瘛?。HSSFWorkbookworkbook=newHSSFWorkbook();HSSFSheetsheet=workbook.createSheet();HSSFRowrow=sheet.getRow(0);HSSFCellcell=下面來(lái)看看如何在取得現(xiàn)有行或者在新創(chuàng)建的行里,再創(chuàng)建一個(gè)單元格。用POI「HSSFRow」類的「createCell」方publicHSSFCellcreateCell(shortUsethistocreatenewcellswithintherowandreturnThecellthatisreturnedisaCELL_TYPE_BLANK.ThetypecanbechangedeitherthroughcallingsetCellValueorsetCellType.column--thecolumnnumberthiscellrepresentsHSSFCellahighlevelrepresentationofthecreatedimportimportorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.hssf.usermodel.HSSFSheet;importorg.apache.poi.hssf.usermodel.HSSFRow;importorg.apache.poi.hssf.usermodel.HSSFCell;publicclasspublicstaticvoidmain(String[]args){HSSFWorkbookworkbook=newHSSFWorkbook();HSSFSheetsheet=HSSFRowrowsheet.createRow(1);//創(chuàng)建序號(hào)為1行,第2HSSFCellcellrow.createCell((short)2);//創(chuàng)建序號(hào)為2行第3FileOutputStreamout=null;out=newFileOutputStream("sample.xls");}catch(IOExceptione){try}catch(IOExceptione){}}}}上面的例子里,先創(chuàng)建一個(gè)工作表Sheet,然后在工作表里只創(chuàng)建第二行,最后再在這一行創(chuàng)建一個(gè)新的單元格,并設(shè)上一個(gè)值。實(shí)行這個(gè)程序會(huì)生成「sample.xls」這樣的Excel看看吧。提供了publicHSSFCellgetCell(shortgetthehssfcellrepresentingagivencolumn(logicalcell)Ifyouaskforacellthatisnotdefined....yougetacellnum-0basedcolumnHSSFCellrepresentingthatcolumnornullif(shortcellnum)取得指定列號(hào)的單元格。如果是不存在的單元格,會(huì)返回「null」。importimportorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.hssf.usermodel.HSSFSheet;importorg.apache.poi.hssf.usermodel.HSSFRow;importorg.apache.poi.hssf.usermodel.HSSFCell;publicclasspublicstaticvoidmain(String[]args){HSSFWorkbookworkbook=newHSSFWorkbook();HSSFSheetsheet=workbook.createSheet();HSSFRowrowsheet.createRow(1);//創(chuàng)建第二行HSSFCellcellrow.createCell((short)2);//創(chuàng)建第二行第三格cell.setCellValue("test");//第二行第三格寫入testfor(inti=0;i<3;i++){HSSFCellc=row.getCell((short)i);if(c==null){System.out.println("第i在System.out.println("第i功}}}}上面的例子里,先做成一行(行號(hào)為1),然后在這一行的第2(行號(hào)為2)創(chuàng)建單元格,最后再?gòu)牡?到第2格,2成有值的Excel像下面那樣準(zhǔn)備一個(gè)Excelimportimportorg.apache.poi.poifs.filesystem.POIFSFileSystem;importorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.hssf.usermodel.HSSFSheet;importorg.apache.poi.hssf.usermodel.HSSFRow;importorg.apache.poi.hssf.usermodel.HSSFCell;publicclasspublicstaticvoidmain(String[]args){FileInputStreamin=null;HSSFWorkbookworkbook=null;in=newFileInputStream("sample.xls");POIFSFileSystemfs=newPOIFSFileSystem(in);workbook=newHSSFWorkbook(fs);}catch(IOExceptione){}catch(IOExceptione){}}HSSFSheetsheetworkbook.getSheetAt(0);//取得第一張HSSFRowrowsheet.getRow(1);//第2for(inti=0;i<3;i++){HSSFCellc=row.getCell((short)i);if(c==null){System.out.println("第i在System.out.println("第i功System.out.println("單元格的值c.getStringCellValue());//getStringCellValue(}}}}單元格的值:cella-21單元格的值:cellc-前面介紹了如何用POI何用POI單元格里設(shè)定值。和之前獲取值一樣,對(duì)于不同類型的值,寫入的方 方booleansetCellValue(boolean setCellValue(java.util.Calendarvalue) setCellValue(java.util.Datevalue)numericsetCellValue(doublevalue)stringsetCellValue(java.lang.String方法名稱相同,但參數(shù)類型不同,這樣的方法有5于日期型的方法,有Calender和Date當(dāng)然,POI也可以寫入Error 方errorvaluesetCellErrorValue(byte setCellFormula(java.lang.String先統(tǒng)一看一下各種方法的DocsetCellValue(boolean寫入boolean用「setCellValue(booleanvalue)publicvoidsetCellValue(booleanvalue)setabooleanvalueforthecellvalue-thebooleanvaluetosetthiscellto.Forformulaswe'llsettheprecalculatedvalue,forbooleanswe'llsetitsvalue.Forothertypeswewillchangethecelltoabooleancellandsetitsvalue.如果對(duì)象單元格不是boolean轉(zhuǎn)換為boolean入setCellValue(java.util.Calendar寫入CalendarsetCellValue(java.util.Calendarvalue)」方法。publicvoidsetCellValue(java.util.Calendarsetadatevalueforthecell.Exceltreatsdatesasnumericsoyouwillneedtoformatthecellasadate.value-thedatevaluetosetthiscellto.Forformulaswe'llsettheprecalculatedvalue,fornumericswe'llsetitsvalue.Forothertypeswewillchangethecelltoanumericcellandsetitsvalue.Calendar話,則自動(dòng)轉(zhuǎn)換setCellValue(java.util.Date寫入DatesetCellValue(java.util.Datevalue)」方法。publicvoidsetCellValue(java.util.Datesetadatevalueforthecell.Exceltreatsdatesasnumericsoyouwillneedtoformatthecellasadate.value-thedatevaluetosetthiscellto.Forformulaswe'llsettheprecalculatedvalue,fornumericswe'llsetitsvalue.Forothertypeswewillchangethecelltoanumericcellandsetitsvalue.Date數(shù)setCellValue(double寫入數(shù)值型使用「setCellValue(doublevalue)」方法。publicvoidsetCellValue(doublevalue)setanumericvalueforthecellvalue-thenumericvaluetosetthiscellto.Forformulaswe'llsettheprecalculatedvalue,fornumericswe'llsetitsvalue.Forothertypeswewillchangethecelltoanumericcellandsetitsvalue.setCellValue(java.lang.String寫入字符串型使用「setCellValue(java.lang.Stringvalue)」方法。publicvoidsetCellValue(java.lang.Stringsetastringvalueforthecell.Pleasenotethatifyouareusingfull16bitunicodeyoushouldcallsetEncoding()first.value-valuetosetthecellto.Forformulaswe'llsettheformulastring,forStringcellswe'llsetitsvalue.Forothertypeswewillchangethecelltoastringcellandsetitsvalue.IfvalueisnullthenwewillchangethecelltoaBlankcell.setCellErrorValue(byte寫入Error「setCellErrorValue(bytevalue)」方法。publicvoidsetCellErrorValue(bytevalue)setaerrorvalueforthecellvalue-theerrorvaluetosetthiscellto.Forformulaswe'llsettheprecalculatedvalue???ISTHISRIGHT???,forerrorswe'llsetitsvalue.Forothertypeswewillchangethecelltoanerrorcellandsetitsvalue.如果對(duì)象單元格不是Error換為Error寫入publicvoidsetCellFormula(java.lang.String-寫入計(jì)算式方法的參數(shù)雖然是字符串,但Doc說(shuō)明也沒(méi)有。importimportorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.hssf.usermodel.HSSFSheet;importorg.apache.poi.hssf.usermodel.HSSFRow;importorg.apache.poi.hssf.usermodel.HSSFCell;importjava.util.Calendar;importimportpublicclasspublicstaticvoidmain(String[]args){HSSFWorkbookworkbook=newHSSFWorkbook();HSSFSheetsheet=workbook.createSheet();HSSFRowrowsheet.createRow(1);//創(chuàng)建第二行HSSFCellcell1row.createCell((short)0);//2,1HSSFCellcell2=row.createCell((short)1);//2,2CalendarcalCalendar.getInstance();//Calendar???cell2.setCellValue(cal);//寫入Calendar型對(duì)象calHSSFCellcell3row.createCell((short)2);//2,3DatedatenewDate期HSSFCellcell4row.createCell((short)3);//2,4HSSFCellcell5row.createCell((short)4);//2.5cell5.setCellValue("o");//寫入oHSSFRowrow2sheet.createRow(2);//第三行HSSFCellcell6row2.createCell((short)0);//3,1FileOutputStreamout=null;out=newFileOutputStream("sample.xls");}catch(IOExceptione){try{}catch(IOExceptione){}}}}如果你現(xiàn)在版的POI開發(fā)包,你會(huì)發(fā)現(xiàn),用POI向單元格里寫入字符串時(shí),如果是中文文字或者日文文字的話,已經(jīng)不需要指定Unicode「HSSFCell」類的「setEncoding」方法已經(jīng)被刪除了。下面是被刪除的方法說(shuō)publicvoidsetEncoding(shortsettheencodingtoeither8or16bit.(US/UKuse8-bit,restofthewesternworlduse16bit)encoding-either PRESSED_UNICODE(0)orENCODING_UTF_16(1)importimportorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.hssf.usermodel.HSSFSheet;importorg.apache.poi.hssf.usermodel.HSSFRow;importorg.apache.poi.hssf.usermodel.H

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論