java操做Excel、word和pdf

有些時候咱們須要讀寫excel和word,或者將文字轉爲pdf那咱們應該怎麼作呢?java

若是須要讀寫excel須要添加包:apache

<!-- 操做excel -->
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>3.15</version>
		</dependency>

若是須要讀寫word須要添加包:app

<!-- 操做word -->
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-scratchpad</artifactId>
			<version>3.15</version>
		</dependency>

若是須要操做pdf,須要添加pdf,須要添加:字體

<!-- pdf相關包 -->
		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itextpdf</artifactId>
			<version>5.5.10</version>
		</dependency>
		<!-- 輸出中文,還要引入下面itext-asian.jar包 -->
		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itext-asian</artifactId>
			<version>5.2.0</version>
		</dependency>
		<!-- 設置pdf文件密碼,還要引入下面bcprov-jdk15on.jar包 -->
		<dependency>
			<groupId>org.bouncycastle</groupId>
			<artifactId>bcprov-jdk15on</artifactId>
			<version>1.54</version>
		</dependency>

而後是如何在代碼中操做excel:this

/**
 * @author panmingshuai
 * @description 
 * @Time 2018年4月2日  下午4:29:08
 *
 */
public class ExcelTest {
	@SuppressWarnings("resource")
	public static void main(String[] args) throws Exception {
		/**
		 * 讀取excel
		 */
//		FileInputStream in = new FileInputStream(new File("E:\\mz.xlsx"));
		//讀取xlsx的excel
//		XSSFWorkbook workbook = new XSSFWorkbook(in);
		//讀取xls的excel
//		HSSFWorkbook workbook = new HSSFWorkbook(in);
		
		//循環遍歷excel表
//		for(int i=0; i<workbook.getNumberOfSheets(); i++){
//			XSSFSheet sheet = workbook.getSheetAt(i);
//			for(int j=0; j<=sheet.getLastRowNum(); j++){
//				XSSFRow row = sheet.getRow(j);
//				for(int k=0; k<row.getLastCellNum(); k++){
//					XSSFCell cell = row.getCell(k);
//					String dm = cell.toString();
//					if(k == row.getLastCellNum()-1){
//						System.out.println(dm);
//					} else {
//						System.out.print(dm);
//					}
//				}
//			}
//		}
		
		//數值轉換的方法
//		XSSFSheet sheet = workbook.getSheetAt(0);
//		XSSFRow row = sheet.getRow(0);
//		XSSFCell cell0 = row.getCell(0);
//		XSSFCell cell1 = row.getCell(1);
//		XSSFCell cell2 = row.getCell(2);
//		System.out.println(Double.valueOf(cell0.toString()) + 10);//浮點數
//		System.out.println(Math.round(Float.valueOf(cell1.toString()))+10);//整數
//		System.out.println(Math.round(Double.valueOf(cell2.toString()))+10);//長整型
		
		
		
		
		/**
		 * 寫入excel
		 */
		XSSFWorkbook workbook = new XSSFWorkbook();
		XSSFSheet sheet = workbook.createSheet();
		XSSFRow row0 = sheet.createRow(0);
		XSSFCell cell0 = row0.createCell(0);
		cell0.setCellValue("pan");
		XSSFCell cell1 = row0.createCell(1);
		cell1.setCellValue(123);
		XSSFCell cell2 = row0.createCell(2);
		cell2.setCellValue(123.2352545);
		
		//單元格合併和樣式設置
		XSSFRow row1 = sheet.createRow(1);
		XSSFCell cell10 = row1.createCell(0);
		XSSFCell cell11 = row1.createCell(1);
		cell10.setCellValue("cell10");
		cell11.setCellValue("cell11");
		
		//爲cell10設置樣式
		XSSFCellStyle cellStyle = workbook.createCellStyle();//單元格樣式
		Font fontStyle = workbook.createFont(); // 字體樣式 
		fontStyle.setBold(true); // 加粗  
        fontStyle.setFontName("黑體"); // 字體  
        fontStyle.setFontHeightInPoints((short) 11); // 大小
        // 將字體樣式添加到單元格樣式中   
        cellStyle.setFont(fontStyle);  
        // 居中  
        cellStyle.setAlignment(HorizontalAlignment.CENTER);  
        //設置邊框
        cellStyle.setBorderBottom(BorderStyle.THIN);  
        cellStyle.setBorderLeft(BorderStyle.THIN);  
        cellStyle.setBorderRight(BorderStyle.THIN);  
        cellStyle.setBorderTop(BorderStyle.THIN);  
        // 爲cell10單元格添加樣式
        cell10.setCellStyle(cellStyle); 
        
        // 合併單元格  
        CellRangeAddress cra =new CellRangeAddress(1, 3, 1, 3); // 起始行, 終止行, 起始列, 終止列  
        sheet.addMergedRegion(cra);  
        //爲cell11設置樣式,由於這時已經合併,因此如今cell11的樣式就是合併單元格的樣式
      	XSSFCellStyle cellStyle1 = workbook.createCellStyle();//單元格樣式
      	//水平居中
      	cellStyle1.setAlignment(HorizontalAlignment.CENTER);
      	//垂直居中
      	cellStyle1.setVerticalAlignment(VerticalAlignment.TOP);
      	cell11.setCellStyle(cellStyle1);
          
        // 使用RegionUtil類爲合併後的單元格添加邊框 ,若是不設置就只有左上角的那個合併前的單元格有上和左的邊框線
        RegionUtil.setBorderBottom(1, cra, sheet); // 下邊框  
        RegionUtil.setBorderLeft(1, cra, sheet); // 左邊框  
        RegionUtil.setBorderRight(1, cra, sheet); // 有邊框  
        RegionUtil.setBorderTop(1, cra, sheet); // 上邊框 
        
        
		
		
		
		File file = new File("E://pan.xlsx");
		FileOutputStream out = FileUtils.openOutputStream(file);
		workbook.write(out);
		out.close();
	}
}

至於代碼的意義,註釋已經很詳細了。excel

接下來是操做word:code

/**
 * @author panmingshuai
 * @description
 * @Time 2018年4月2日 下午5:46:30
 *
 */
public class WordTest {
	@SuppressWarnings("resource")
	public static void main(String[] args) throws Exception {
		/**
		 * 讀取doc文檔
		 */
		// FileInputStream in = FileUtils.openInputStream(new
		// File("E:\\qwe.doc"));
		// HWPFDocument doc = new HWPFDocument(in);
		// Range range = doc.getRange();
		// for(int i=0; i<range.numParagraphs(); i++){
		// System.out.println("---------------------------" +
		// range.getParagraph(i).text());
		// }
		// String docText = range.text();
		// System.out.println(docText);
		// in.close();

		/**
		 * 讀取docx文檔
		 */
		// FileInputStream in = FileUtils.openInputStream(new
		// File("E:\\qwe.docx"));
		// XWPFDocument doc = new XWPFDocument(in);
		// for(XWPFParagraph paragraph : doc.getParagraphs()){
		// System.out.println("-------------" + paragraph.getText());
		// }
		// XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
		// System.out.println(extractor.getText());

		/**
		 * 寫入docx文檔
		 */
		XWPFDocument doc = new XWPFDocument();
		XWPFParagraph para = doc.createParagraph();
		//首行縮進
		para.setIndentationFirstLine(1000);
		// 一個XWPFRun表明具備相同屬性的一個區域。
		XWPFRun run = para.createRun();
		run.setBold(true); // 加粗
		run.setText("加粗的內容");
		run = para.createRun();
		run.setColor("FF0000");
		run.setText("紅色的字。");
		run = para.createRun();
		run.setFontSize(17);
		run.setText("17號的字");
		OutputStream os = FileUtils.openOutputStream(new File("E:\\qwe123.docx"));
		doc.write(os);
		os.close();
		
		
		
		
		/**
		 * XWPFParagraph設置樣式:
		 * 
		 * 
		 * //setAlignment()指定應適用於此段落中的文本的段落對齊方式。CENTER LEFT...
		 * //p1.setAlignment(ParagraphAlignment.LEFT);
		 * //p1.setBorderBetween(Borders.APPLES);
		 * //p1.setBorderBottom(Borders.APPLES);
		 * //p1.setBorderLeft(Borders.APPLES);指定應顯示在左邊頁面指定段周圍的邊界。
		 * //p1.setBorderRight(Borders.ARCHED_SCALLOPS);指定應顯示在右側的頁面指定段周圍的邊界。
		 * //p1.setBorderTop(Borders.ARCHED_SCALLOPS);指定應顯示上方一組有相同的一組段邊界設置的段落的邊界。這幾個是對段落之間的格式的統一,至關於格式刷
		 * //p1.setFirstLineIndent(99);//---正文寬度會稍微變窄
		 * //p1.setFontAlignment(1);//---段落的對齊方式 1左 2中 3右 4往上 左 不可寫0和負數
		 * //p1.setIndentationFirstLine(400);//---首行縮進,指定額外的縮進,應適用於父段的第一行。
		 * //p1.setIndentationHanging(400);//---首行前進,指定的縮進量,應經過第一行回到開始的文本流的方向上移動縮進從父段的第一行中刪除。
		 * //p1.setIndentationLeft(400);//---整段縮進(右移)指定應爲從左到右段,該段的內容的左邊的緣和這一段文字左邊的距和右邊文本邊距和左段權中的那段文本的右邊緣之間的縮進,
		 * 		若是省略此屬性,則應假定其值爲零。
		 * //p1.setIndentationRight(400);//---指定應放置這一段,該段的內容從左到右段的右邊緣的正確文本邊距和右邊文本邊距和左段權中的那段文本的右邊緣之間的縮進,
		 * 		若是省略此屬性,則應假定其值爲零。
		 * //p1.setIndentFromLeft(400);//---整段右移
		 * //p1.setIndentFromRight(400);
		 * //p1.setNumID(BigInteger.TEN);
		 * //p1.setPageBreak(true);//--指定當渲染此分頁視圖中的文檔,這一段的內容都呈如今文檔中的新頁的開始。
		 * //p1.setSpacingAfter(6);//--指定應添加在文檔中絕對單位這一段的最後一行以後的間距。
		 * //p1.setSpacingAfterLines(6);//--指定應添加在此線單位在文檔中的段落的最後一行以後的間距。
		 * //p1.setSpacingBefore(6);//--指定應添加上面這一段文檔中絕對單位中的第一行的間距。
		 * //p1.setSpacingBeforeLines(6);//--指定應添加在此線單位在文檔中的段落的第一行以前的間距。
		 * //p1.setSpacingLineRule(LineSpacingRule.AT_LEAST);//--指定行之間的間距如何計算存儲在行屬性中。
		 * //p1.setStyle("");//--此方法提供了樣式的段落,這很是有用.
		 * //p1.setVerticalAlignment(TextAlignment.CENTER);//---指定的文本的垂直對齊方式將應用於此段落中的文本
		 * //p1.setWordWrapped(true);//--此元素指定是否消費者應中斷超過一行的文本範圍,經過打破這個詞 (打破人物等級) 的兩行或經過移動到下一行 (在詞彙層面上打破) 這個詞的拉丁文字。
		 * //XWPFRun r1=p1.createRun();//p1.createRun()將一個新運行追加到這一段
		 * //setText(String value)或setText(String value,int pos)
		 * //r1.setText(data);
		 * //r1.setTextPosition(20);//這個至關於設置行間距的,具體這個20是怎麼算的,不清楚,此元素指定文本應爲此運行在關係到周圍非定位文本的默認基線升降的量。
		 * 		不是真正意義上的行間距
		 * //r1.setStrike(true);//---設置刪除線的,坑人!!!
		 * //r1.setStrikeThrough(true);---也是設置刪除線,可能有細微的區別吧
		 * //r1.setEmbossed(true);---變的有重影(變黑了一點)
		 * //r1.setDoubleStrikethrough(true);---設置雙刪除線
		 * //r1.setColor("33CC00");//---設置字體顏色 ★
		 * //r1.setFontFamily("fantasy");
		 * //r1.setFontFamily("cursive");//---設置ASCII(0 - 127)字體樣式 
		 * //r1.setBold(jiacu);//---"加黑加粗"
		 * //r1.setFontSize(size);//---字體大小
		 * //r1.setImprinted(true);//感受與setEmbossed(true)相似,有重影
		 * //r1.setItalic(true);//---文本會有傾斜,是一種字體?
		 * //r1.setShadow(true);//---文本會變粗有重影,與前面兩個有重影效果的方法感受沒什麼區別
		 * //r1.setSmallCaps(true);//---改變了  英文字母  的格式
		 * //r1.setSubscript(VerticalAlign.BASELINE);//---valign垂直對齊的
		 * //r1.setUnderline(UnderlinePatterns.DASH);//--填underline type設置下劃線
		 * //document.createTable(2, 2);//--建立一個制定行列的表
		 * //document.enforceReadonlyProtection();//--強制執行制度保護
		 * //r1.setDocumentbackground(doc, "FDE9D9");//設置頁面背景色
		 * //r1.testSetUnderLineStyle(doc);//設置下劃線樣式以及突出顯示文本
		 * //r1.addNewPage(doc, BreakType.PAGE);
		 * //r1.testSetShdStyle(doc);//設置文字底紋
		 */
	}
}

而後是操做pdf:xml

/**
 * @author panmingshuai
 * @description 
 * @Time 2018年4月3日  上午10:27:10
 *
 */
public class PdfTest {
	public static void main(String[] args) throws Exception {
		// 一、新建document對象
        Document document = new Document();
        

        // 二、創建一個書寫器(Writer)與document對象關聯,經過書寫器(Writer)能夠將文檔寫入到磁盤中。
        // 建立 PdfWriter 對象 第一個參數是對文檔對象的引用,第二個參數是文件的實際名稱,在該名稱中還會給出其輸出路徑。
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("E:\\pan.pdf"));
        
        
        // 給PDF文件設置密碼,須要引入bcprov-jdk15on.jar包
        //用戶密碼
        String userPassword = "123456";
        //擁有者密碼(能夠編輯pdf,例如插入頁眉之類的)
        String ownerPassword = "pan";
        writer.setEncryption(userPassword.getBytes(), ownerPassword.getBytes(), PdfWriter.ALLOW_PRINTING,PdfWriter.ENCRYPTION_AES_128);
        

        //三、打開文檔
        document.open();
        
        
        //四、PDF中設置段落樣式,輸出中文內容,必須引入itext-asian.jar
        //中文字體,解決中文不能顯示問題
        BaseFont bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
        
        //藍色字體
        Font blueFont = new Font(bfChinese);
        blueFont.setColor(BaseColor.BLUE);
        //段落文本
        Paragraph paragraphBlue = new Paragraph("藍色段落", blueFont);
        document.add(paragraphBlue);
     
        //綠色字體
        Font greenFont = new Font(bfChinese);
        greenFont.setColor(BaseColor.GREEN);
        //建立章節(會另起一頁)
        Paragraph chapterTitle = new Paragraph("段落標題xxxx", greenFont);
        Chapter chapter1 = new Chapter(chapterTitle, 1);
        chapter1.setNumberDepth(0);
       
        Paragraph sectionTitle = new Paragraph("部分標題", greenFont);
        Section section1 = chapter1.addSection(sectionTitle);
     
        Paragraph sectionContent = new Paragraph("部份內容", blueFont);
        section1.add(sectionContent);
        
        //將章節添加到文章中
        document.add(chapter1);
        
        
        //五、添加圖片
        //圖片1
        Image image1 = Image.getInstance("E:\\123.jpg");
        //設置圖片位置的x軸和y周
        image1.setAbsolutePosition(100f, 550f);
        //設置圖片的寬度和高度
        image1.scaleAbsolute(200, 200);
        //將圖片1添加到pdf文件中
        document.add(image1);
        //圖片2
        Image image2 = Image.getInstance(new URL("http://b.hiphotos.baidu.com/image/pic/item/6159252dd42a28341d491d0057b5c9ea14cebfc9.jpg"));
        //設置圖片位置的x軸和y周
        image2.setAbsolutePosition(100f, 300f);
        //設置圖片的寬度和高度
        image2.scaleAbsolute(200, 200);
        //將圖片2添加到pdf文件中
        document.add(image2);
        
        
        //六、添加表格:
        //添加一個3列的表
        PdfPTable table = new PdfPTable(3); 
        table.setWidthPercentage(100); // 寬度100%填充
        table.setSpacingBefore(10f); // 前間距
        table.setSpacingAfter(10f); // 後間距

        List<PdfPRow> listRow = table.getRows();
        //設置列寬
        float[] columnWidths = { 1f, 2f, 3f };
        table.setWidths(columnWidths);
        
        //行1
        PdfPCell cells1[]= new PdfPCell[3];
        PdfPRow row1 = new PdfPRow(cells1);
       
        //單元格
        cells1[0] = new PdfPCell(new Paragraph("111"));//單元格內容
        cells1[0].setBorderColor(BaseColor.BLUE);//邊框顏色
        cells1[0].setPaddingLeft(20);//左填充20
        cells1[0].setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
        cells1[0].setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中

        cells1[1] = new PdfPCell(new Paragraph("222"));
        cells1[2] = new PdfPCell(new Paragraph("333"));
        
        //行2
        PdfPCell cells2[]= new PdfPCell[3];
        PdfPRow row2 = new PdfPRow(cells2);
        cells2[0] = new PdfPCell(new Paragraph("444"));

        //把第一行添加到集合
        listRow.add(row1);
        listRow.add(row2);
        //把表格添加到文件中
        document.add(table);
        
        
        //添加有序列表
        com.itextpdf.text.List orderedList = new com.itextpdf.text.List(com.itextpdf.text.List.ORDERED);
        orderedList.add(new ListItem("Item one"));
        orderedList.add(new ListItem("Item two"));
        orderedList.add(new ListItem("Item three"));
        document.add(orderedList);
        
        
        //設置屬性
        //標題
        document.addTitle("this is a title");
        //做者
        document.addAuthor("pan");
        //主題
        document.addSubject("this is subject");
        //關鍵字
        document.addKeywords("Keywords");
        //建立時間
        document.addCreationDate();
        //應用程序
        document.addCreator("pan.com");

        // 關閉文檔
        document.close();
        //關閉書寫器
        writer.close();
	}
}

完畢。對象

相關文章
相關標籤/搜索