有些时候我们需要读写excel和word,或者将文字转为pdf那我们应该怎么做呢?
如果需要读写excel需要添加包:
<!-- 操作excel -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
如果需要读写word需要添加包:
<!-- 操作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:
/**
* @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();
}
}
至于代码的意义,注释已经很详细了。
接下来是操作word:
/**
* @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:
/**
* @author panmingshuai
* @description
* @Time 2018年4月3日 上午10:27:10
*
*/
public class PdfTest {
public static void main(String[] args) throws Exception {
// 1、新建document对象
Document document = new Document();
// 2、建立一个书写器(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);
//3、打开文档
document.open();
//4、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);
//5、添加图片
//图片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);
//6、添加表格:
//添加一个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();
}
}
完毕。