项目第四天beforeclass课前首先从Workbook开始我们的POI编程之旅要生成一个_第1页
项目第四天beforeclass课前首先从Workbook开始我们的POI编程之旅要生成一个_第2页
项目第四天beforeclass课前首先从Workbook开始我们的POI编程之旅要生成一个_第3页
项目第四天beforeclass课前首先从Workbook开始我们的POI编程之旅要生成一个_第4页
项目第四天beforeclass课前首先从Workbook开始我们的POI编程之旅要生成一个_第5页
已阅读5页,还剩89页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

HSSFWorkbook(创建excel首先从Workbook们的POIWorkbook,需要用到HSSFWorkbookpublicclassHSSFWorkbookextendsCreatesnewHSSFWorkbookfromscratch(starthere!)HSSFWorkbook(java.io.InputStreams)HSSFWorkbook(java.io.InputStreams,booleanpreserveNodes)CompaniontoHSSFWorkbook(POIFSFileSystem),thisconstructsthePOIfilesystemaroundyourHSSFWorkbook(POIFSFileSystemfs)HSSFWorkbook(POIFSFileSystemfs,booleanpreserveNodes)givenaPOIPOIFSFileSystemobject,readinitsWorkbookandpopulatethehighandlowlevel我们用第一个构建器来生成一个WorkbookpublicCreatesnewHSSFWorkbookfromscratch(startHSSFWorkbookworkbook=new接下来再来对生成的Workbook「HSSFWorkbook」类的「write」方法:publicvoidwrite(java.io.OutputStreamstream)throwsMethodwrite-writeoutthisworkbooktoanOutputstream.ConstructsanewPOIPOIFSFileSystem,passesintheworkbookbinaryrepresentationandwritesitout.stream--thejavaOutputStreamyouwishtowritetheXLStojava.io.IOException-ifanythingcan'tbeimportimportpublicclasspublicstaticvoidmain(String[]HSSFWorkbookworkbooknewHSSFWorkbook();//创建一个空白的FileOutputStreamout=null;out=newworkbook.write(out);//调用HSSFWorkbookwrite法}catch(IOExceptione){try{}catch(IOExceptione){}}}}POIFSFileSystem类(excel表格这次我们用POI在的Workbook。因为没有现成的方法,所以只能再次利用HSSFWorkbook方publicHSSFWorkbook(POIFSFileSystemfs)throws-POIFSFileSystempublicclassPOIFSFileSystemextendsjava.lang.ObjectimplementsConstructor,intendedforPOIFSFileSystem(java.io.InputStreamCreateaPOIFSFileSystemfromanpublicPOIFSFileSystem(java.io.InputStreamstream)throwsCreateaPOIFSFileSystemfromanstream-theInputStreamfromwhichtoreadthedatajava.io.IOException-onerrorsreading,oroninvalid参数设定为读入Excel「InputStreamFileInputStreamin=newFileInputStream("sample.xls");//文件输入流POIFSFileSystemfsnewPOIFSFileSystem(in)poifsfileSystemHSSFWorkbookwb=newHSSFWorkbook(fs);通过POIFSFileSystemExcel文件下面就实际做一下如何Excel文件。importimportorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.poifs.filesystem.POIFSFileSystem;publicclasspublicstaticvoidmain(String[]args){FileInputStreamin=null;HSSFWorkbookworkbook=null;innewFileInputStream("sample1.xls");//将excel件转为输入POIFSFileSystemfsnewPOIFSFileSystem(in);//构建POIFSFileSystem构workbooknewHSSFWorkbook(fs);//创建个workbook,根据POIFSFileSystem}catch(IOExceptione){}catch(IOExceptione){}}FileOutputStreamout=null;out=newFileOutputStream("sample2.xls");}catch(IOExceptione){try{}catch(IOExceptione){}}}}关于publicclassHSSFSheetextendsprotectedHSSFSheet(WorkbookCreatesnewHSSFSheet–calledbyHSSFWtectedHSSFSheet(Workbookbook,Sheetsheet)CreatesanHSSFSheetrepresentingthegivenSheet虽然有两个构建器,但都是protected新建Sheet,只能通过Workbook。SheetWorkbook新建SheetHSSFWorkbook」类的「createSheet」的方法,详细可以参照「在Workbook创Sheet」。HSSFWorkbookworkbooknewHSSFWorkbook();//创建个空白的workbookHSSFSheetsheet=workbook.createSheet()sheet现有的对于在Workbook已经存在的Sheet来说,可以用「HSSFWorkbook」类的「getSheet」方法来publicHSSFSheetgetSheet(java.lang.Stringname)Getsheetwiththegivennamename-ofthesheetHSSFSheetwiththenameprovidedornullifitdoesnot(java.lang.Stringname)参数为SheetHSSFWorkbookworkbook=newHSSFSheetsheet=workbook.getSheet("sheet1")//名称为sheet1的publicHSSFSheetgetSheetAt(intGettheHSSFSheetobjectatthegivenindex-ofthesheetnumber(0-basedphysical&logical)HSSFSheetattheprovidedindex(intindex)参数为sheet序号HSSFWorkbookworkbook=newHSSFSheetsheet=workbook.getSheetAt(1);//序号为1的sheet(第二张Workbook要在Workbook建一个Sheet,可以使用「HSSFWorkbook」类的「createSheet」方法。publicHSSFSheetcreateanHSSFSheetforthisHSSFWorkbook,addsittothesheetsandreturnsthehighlevelrepresentation.UsethistocreatenewHSSFSheetrepresentingthenewpublicHSSFSheetcreateSheet(java.lang.StringcreateanHSSFSheetforthisHSSFWorkbook,addsittothesheetsandreturnsthehighlevelrepresentation.Usethistocreatenewsheetname-sheetnametosetforthesheet.HSSFSheetrepresentingthenewsheet.创建的Sheet「HSSFSheet」类对象返回。importimportpublicclasspublicstaticvoidmain(String[]args){HSSFWorkbookworkbook=newHSSFWorkbook();workbook.createSheet();//创建workbooksheetFileOutputStreamout=null;out=newFileOutputStream("sample.xls");}catch(IOExceptione){try{}catch(IOExceptione){}}}}如果没有设定Sheet会从0设定为Sheet0,Sheet1,设定为test以创建testSheetWorkbook要Workbook里现有的Sheet来创建新的Sheet,可以使用「HSSFWorkbook」类的「cloneSheet」方法。publicHSSFSheetcloneSheet(intcreateanHSSFSheetfromanexistingsheetintheHSSFSheetrepresentingthecloned指定要的Sheet序列号。 前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){}}}}可以看出,两个Sheet被成功。被的Sheet名格式是「原Sheet名(序列号)」。顺便一提的是,如果你手动在Excel里进行复制的话,被的Sheet名的格式是「原Sheet名(序列号)」。也就是原Sheet名和(序列号)之间有一个半角空格。Workbook要从Workbook删除Sheet,可以使用「HSSFWorkbook」类的方法「removeSheetAt」。publicvoidremoveSheetAt(intindex)removessheetatthegivenindexindex-ofthesheet(0-(intindex)指定要删除Sheet号publicintgetSheetIndex(java.lang.Stringname)Returnstheindexofthesheetbyhisnamename-thesheetnameindexofthesheet(0(java.lang.Stringname)参数请指定要删除的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」,设定Sheet看Sheet0=Sheet2=我们发现中间的Sheet面的Sheet往前移一个,总之会维持从0要改变现有Sheet新建Sheet「HSSFWorkbook」类的「setSheetName」方法publicvoidsetSheetName(intsheet,java.lang.Stringsetthesheetname.WillthrowIllegalArgumentExceptionifthenameisgreaterthan31charsorcontains/\?*[]sheet-number(0参数:(intsheet)指定要改变的Sheet(java.lang.Stringname)为要改变的名称,设置名称时,最大长度是指定汉字SheetpublicvoidsetSheetName(intsheet,java.lang.Stringshort-static staticbyte 参数(intsheet,java.lang.Stringname,shortencoding)intsheet sheet号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」方法创建新的SheetencodingSheet能先新建一个Sheet,然后再对该SheetpublicvoidsetColumnWidth(shortcolumn,shortwidth)setthewidth(inunitsof1/256thofacharacterwidth)column--thecolumntoset(0-width--thewidthinunitsof1/256thofacharacter(shortcolumn)指定列的序列号(shortwidth)指定列的宽度。宽度如果指定1字的1/256(也就是说一个文字占256),41024。publicshortgetColumnWidth(shortgetthewidth(inunitsof1/256thofacharacterwidthcolumn--thecolumntoset(0-based)width-thewidthinunitsof1/256thofacharacter(shortcolumn)指定列的序列号自己动手做一下吧。仍然按照下图准备一个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]);}//循环获取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宽一个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有时我们可能会手动去调整工作表Sheet例,用POI「HSSFSheet」类的「setZoom」方publicvoidsetZoom(intnumerator,intSetsthezoommagnicationforthesheet.Thezoomisexpressedasafraction.Forexampletoexpressazoomof75%use3forthenumeratorand4forthedenominator.numerator-Thenumeratorforthezoommagnification.denominator-Thedenominatorforthezoommagnification.(intnumerator,intdenominator)参数,这样就可以指定显示比例了,指定方法是用”numerator”÷”denominator”,比方说「setZoom(2,1)」就是设定为200%的比例,「setZoom(34)」就是设定为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);//取得序号为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,动手做做看,还是使用原来的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 构造方protectedprotectedHSSFRow(Workbookbook,Sheetsheet,introwNum)CreatesnewHSSFRowfromtectedHSSFRow(Workbookbook,Sheetsheet,RowRecordrecord)CreatesanHSSFRowfromalowlevelRowRecordobject.虽然有三个,但每一个都是protected使用它的构造方法,而是用SheetHSSFWorkbookworkbook=newHSSFWorkbook();HSSFSheetsheet=workbook.createSheet();HSSFRowrow=sheet.createRow(0);在工作表里取得行,使用「HSSFSheet」类的「getRow」方法,详细内容你可以参照一下『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行号System.out.println("Totalsheet.getPhysicalNumberOfRowsngetPhysicalNumberOfRows()获取sheet数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格,但还不能直接往这些单元格设值。要想往这些单元格里设值,你还publicHSSFRowcreateRow(intCreateanewrowwithinthesheetandreturnthehighlevelrepresentationrownum-rownumberHighlevelHSSFRowobjectrepresentingarowinthe(intrownum)创建指定行号的行。行号是从0最大是65535,可以支持65536返回的值是「HSSFRow」类对创建方法很多,要说详细挺复杂。比方说,即使第一行(行号0)和第二行不创建,也能直接创建第三行。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();//创建个空白的workbookHSSFSheetsheet=workbook.createSheet();//创建个空白的sheetHSSFRowrowsheet.createRow(2);//创建行号为2行,excelHSSFCellcellrow.createCell((short)0);//创建上面行的第一个单元格cell.setCellValue("test");//将test元格FileOutputStreamout=null;out=newFileOutputStream("sample.xls");}catch(IOExceptione){try{}catch(IOExceptione){}}}}在上面的程序里,生成一个Sheet,然后单独创建了第三行(行号为2),接着又创建了一个单元格,最后给这个单元格设了值。执行行要取得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);//序号为0的sheetfor(inti=0;i<3;i++){HSSFRowr=sheet.getRow(i);if(r==null){System.out.println("第iSystem.out.println("第i。}}}}0功1功这一次从已经取得的行里获取单元格的值。仍然使用刚才的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);//序号为0的sheetHSSFRowrow=sheet.getRow(1);//取得sheet二行(行号1)HSSFCellcell=row.getCell((short)1);//取得第二行,第二格(单元格号1)}}最后,再来试试看,在现有的行上,用「createRow」方法创建一行看看会是什么结果。还是使用刚才的Excel在第二行上创建一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);//在已经有第二行的情况下再建第二行HSSFCellcell=row.getCell((short)1);//取得新建第二行的值}}Exceptioninthread"main"java.lang.NullPointerExceptionatPOISample.main(POISample.java:35)发生了空指针异常。本来对于已经存在的行用「createRow」方法进行创建行操作,可能你会以为会原来的行,但事实并非如此。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:指定要移动的行的范围从「startRow」行到「endRow」行。intn:「n」如果是正数就往下移动的行数,如果为负,就往上移动。按下图准备一个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);//第二行和第三行向下移动两行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);//第二行和第三行保留原来高度向下移动两行,原栏位恢复默认高度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.同之前一样,虽然有三个构造方法,但都是protected型的,所以直接用构造方法创建单元格行不通,只能通过行来创建单元格。HSSFWorkbookworkbook=newHSSFWorkbook();HSSFSheetsheet=workbook.createSheet();HSSFRowrow=sheet.createRow(0);HSSFCellcell=要某一行现有的单元格,使用「HSSFRow」类的「getCell」方法,详细请参照『单元格』。HSSFWorkbookworkbook=newHSSFWorkbook();HSSFSheetsheet=workbook.createSheet();HSSFRowrow=sheet.getRow(0);HSSFCellcell=下面来看看如何在取得现有行或者在新创建的行里,再创建一个单元格。用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);//创建序号为1行,第2HSSFCellcellrow.createCell((short)2);//创建序号为2行第3FileOutputStreamout=null;out=newFileOutputStream("sample.xls");}catch(IOExceptione){try}catch(IOExceptione){}}}}上面的例子里,先创建一个工作表Sheet,然后在工作表里只创建第二行,最后再在这一行创建一个新的单元格,并设上一个值。实行这个程序会生成「sample.xls」这样的Excel看看吧。提供了publicHSSFCellgetCell(shortgetthehssfcellrepresentingagivencolumn(logicalcell)Ifyouaskforacellthatisnotdefined....yougetacellnum-0basedcolumnHSSFCellrepresentingthatcolumnornullif(shortcellnum)取得指定列号的单元格。如果是不存在的单元格,会返回「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);//创建第二行HSSFCellcellrow.createCell((short)2);//创建第二行第三格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功}}}}上面的例子里,先做成一行(行号为1),然后在这一行的第2(行号为2)创建单元格,最后再从第0到第2格,2成有值的Excel像下面那样准备一个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单元格里设定值。和之前获取值一样,对于不同类型的值,写入的方 方booleansetCellValue(boolean setCellValue(java.util.Calendarvalue) setCellValue(java.util.Datevalue)numericsetCellValue(doublevalue)stringsetCellValue(java.lang.String方法名称相同,但参数类型不同,这样的方法有5于日期型的方法,有Calender和Date当然,POI也可以写入Error 方errorvaluesetCellErrorValue(byte setCellFormula(java.lang.String先统一看一下各种方法的DocsetCellValue(boolean写入boolean用「setCellValue(booleanvalue)publicvoidsetCellValue(booleanvalue)setabooleanvalueforthecellvalue-thebooleanvaluetosetthiscellto.Forformulaswe'llsettheprecalculatedvalue,forbooleanswe'llsetitsvalue.Forothertypeswewillchangethecelltoabooleancellandsetitsvalue.如果对象单元格不是boolean转换为boolean入setCellValue(java.util.Calendar写入CalendarsetCellValue(java.util.Calendarvalue)」方法。publicvoidsetCellValue(java.util.Calendarsetadatevalueforthecell.Exceltreatsdatesasnumericsoyouwillneedtoformatthecellasadate.value-thedatevaluetosetthiscellto.Forformulaswe'llsettheprecalculatedvalue,fornumericswe'llsetitsvalue.Forothertypeswewillchangethecelltoanumericcellandsetitsvalue.Calendar话,则自动转换setCellValue(java.util.Date写入DatesetCellValue(java.util.Datevalue)」方法。publicvoidsetCellValue(java.util.Datesetadatevalueforthecell.Exceltreatsdatesasnumericsoyouwillneedtoformatthecellasadate.value-thedatevaluetosetthiscellto.Forformulaswe'llsettheprecalculatedvalue,fornumericswe'llsetitsvalue.Forothertypeswewillchangethecelltoanumericcellandsetitsvalue.Date数setCellValue(double写入数值型使用「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.如果对象单元格不是Error换为Error写入publicvoidsetCellFormula(java.lang.String-写入计算式方法的参数虽然是字符串,但Doc说明也没有。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);//创建第二行HSSFCellcell1row.createCell((short)0);//2,1HSSFCellcell2=row.createCell((short)1);//2,2CalendarcalCalendar.getInstance();//Calendar???cell2.setCellValue(cal);//写入Calendar型对象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){}}}}如果你现在版的POI开发包,你会发现,用POI向单元格里写入字符串时,如果是中文文字或者日文文字的话,已经不需要指定Unicode「HSSFCell」类的「setEncoding」方法已经被删除了。下面是被删除的方法说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. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论