package com.epf.transfer.utils;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import jxl.Cell;
import jxl.Range;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ExeclToPdf {
private static String wordTemplatePath;
@Value("${wordTemplatePath}")
public void setWordTemplatePath(String wordTemplatePath){
ExeclToPdf.wordTemplatePath = wordTemplatePath;
}
public static void main(String[] args) throws DocumentException, IOException {
Document document = new Document(PageSize.A1,0,0,50,0);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("E:/PdfTable3.pdf"));
//字体设置
/*
* 由于itext不支持中文,所以需要进行字体的设置,我这里让itext调用windows系统的中文字体,
* 找到文件后,打开属性,将文件名及所在路径作为字体名即可。
*/
//创建BaseFont对象,指明字体,编码方式,是否嵌入
BaseFont bf=BaseFont.createFont("C:\\Windows\\Fonts\\simkai.ttf", BaseFont.IDENTITY_H, false);
//创建Font对象,将基础字体对象,字体大小,字体风格
Font font=new Font(bf,13, Font.NORMAL);
int rowNum = 0;
int colNum = 0;
try {
Workbook workbook=Workbook.getWorkbook(new File("C:\\Users\\Administrator\\AppData\\Local\\Temp\\00b9ecd5-3efb-4c0d-b266-c2a7742ab1e38088562437964126555.xls"));
Sheet sheet=workbook.getSheet(1);
int column=sheet.getColumns();
//下面是找出表格中所有的空列,并记录下标,创建table时不会存在多余的列,并在遍历表格(sheet)时跳过空列
List<Integer> nullCol = new ArrayList<>();
List<Integer> nullRow = new ArrayList<>();
for(int j=0;j<sheet.getColumns();j++){
int nullColNum = 0;
int temp1 = sheet.getRows();
for(int i=0;i<sheet.getRows();i++){
Cell cell=sheet.getCell(j, i);
String str = cell.getContents();
if(str == null || "".equals(str)){
nullColNum ++ ;
}
}
if(nullColNum == sheet.getRows()){
nullCol.add(j);
//记录真实列数
column--;
}
}
//下面是找出表格中所有的空行,并记录下标,创建table时不会存在多余的行,并在遍历表格(sheet)时跳过空行
for(int i=0;i<sheet.getRows();i++){
int nullRowNum = 0;
for(int j=0;j<sheet.getColumns();j++){
Cell cell=sheet.getCell(j, i);
String str = cell.getContents();
if(str == null || "".equals(str)){
nullRowNum ++ ;
}
}
if(nullRowNum == sheet.getColumns()){
nullRow.add(i);//此处是根据列来创建表格的,所以没有记录减去空行
}
}
//创建一个对应列数的表格(此列数不会存在多余,因为前面去除了空列)
PdfPTable table=new PdfPTable(column);
table.setTotalWidth(650);//设置表格的总宽度
//表格多少列,数组就有多长
// float[] columnWidth = {60,60,80,80,60,60,60,60,60,60,60,60,80,80,60,60,60,60,60,60,60,60};
float[] columnWidth = {100,70,70,70,70,70,70,70,70,70,110,70,70,70,70,70,70,70,70};
table.setTotalWidth(columnWidth);//设置表格的各列宽度
table.setLockedWidth(true);
Range[] ranges = sheet.getMergedCells();
PdfPCell cell1=new PdfPCell();
for(int i=0;i<sheet.getRows();i++){
if(nullRow.contains(i)){ //数组中是否包含 i 这个值,如果包含 说明这一行是空行,所以就跳过这一行
continue;
}
for(int j=0;j<sheet.getColumns();j++){
if(nullCol.contains(j)){ //数组中是否包含 i 这个值,如果包含 说明这一行是空列,所以就跳过这一列
continue;
}
boolean flag = true;
Cell cell=sheet.getCell(j, i); //经过空行和空列的判断之后,这个表格不会是空的,所以取出表格
String str = cell.getContents(); //获取表格内容
for(Range range : ranges){
//合并的单元格判断和处理,遍历这个ranges数组判断当前获取到的这个表格是否是合并的单元格,如果是,就进入合并操作,
//如果没有一个匹配说这个表格不是合并单元格,就执行普通单元格操作
int temp1 = range.getTopLeft().getColumn(); //获取左边的列数
int temp2 = range.getBottomRight().getColumn();//获取右边的列数
int temp3 = range.getTopLeft().getRow(); //此行上方距第一行有多少行
int temp4 = range.getBottomRight().getRow();//此行下方距第一行有多少行 ,二者相减就是要合并的行数
if(j >= range.getTopLeft().getColumn() && j <= range.getBottomRight().getColumn() && i >= range.getTopLeft().getRow() && i <= range.getBottomRight().getRow()){
if(str == null || "".equals(str)){
flag = false;
break;
}
rowNum = range.getBottomRight().getRow() - range.getTopLeft().getRow()+1;
colNum = range.getBottomRight().getColumn() - range.getTopLeft().getColumn()+1;
if(rowNum > colNum){ //判断是合并列,还是合并行,此处是合并行
cell1 = mergeRow(str, font, rowNum);
cell1.setColspan(colNum);
table.addCell(cell1);
}else { //这里是合并列
cell1 = mergeCol(str, font, colNum);
cell1.setRowspan(rowNum);
table.addCell(cell1);
}
flag = false;
break;
}
}
//执行普通单元格填充操作
if(flag){
table.addCell(getPDFCell(str,font));
}
}
}
document.open();
document.add(table);
workbook.close();
document.close();
writer.close();
} catch (BiffException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* execl转Pdf
* @author myw
* @date 2020年3月20日15:9:39
* @param hssfWorkbook
* @param sheetNum
* @return
* @throws Exception
*/
public static String execlToPdf(HSSFWorkbook hssfWorkbook, int sheetNum){
if(hssfWorkbook==null){
return "";
}
try{
int index = wordTemplatePath.indexOf(":");
String temp = wordTemplatePath.substring(0,index+1);
//把HSSFWorkbook写入文件,再打开,使用jxl解析
File file = new File(temp+"/temp"+".xls");
FileOutputStream fileOut = new FileOutputStream(file);
hssfWorkbook.write(fileOut);
fileOut.flush();
return handlerDocument(temp,file,sheetNum);
}catch(Exception o){
o.printStackTrace();
}
return null;
}
/**
* execl转Pdf
* @author myw
* @date 2020年3月19日14:37:37
* @param file
* @param sheetNum
* @return
* @throws Exception
*/
public static String execlToPdf(File file,int sheetNum){
if(!(file.isFile())){
return "";
}
String temp = file.getPath();
int index = temp.indexOf(":");
String temp2 = temp.substring(0,index+1);
return handlerDocument(temp2,file,sheetNum);
}
/**
* 对document的处理
* @author myw
* @date 2020年3月20日17:7:54
* @param tempPath
* @param file
* @param sheetNum
* @return
*/
public static String handlerDocument(String tempPath,File file,int sheetNum){
String path = tempPath+"/pdfTable.pdf";
try {
Document document = new Document(PageSize.A1,0,0,50,0);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(path));
document.open();
Workbook workbook=Workbook.getWorkbook(file);
for(int k=0;k<sheetNum;k++){
Sheet sheet=workbook.getSheet(k);
handlerSheet(sheet,document);
}
document.close();
workbook.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
return path;
}
/**
* 把sheet写入文档中
* @author myw
* @date 2020年3月20日17:4:45
* @param sheet
* @param document
* @throws Exception
*/
public static void handlerSheet(Sheet sheet,Document document)throws Exception{
//字体设置
/*
* 由于itext不支持中文,所以需要进行字体的设置,我这里让itext调用windows系统的中文字体,
* 找到文件后,打开属性,将文件名及所在路径作为字体名即可。
*/
//创建BaseFont对象,指明字体,编码方式,是否嵌入 C:\Windows\Fonts\simkai.ttf
BaseFont bf=BaseFont.createFont(wordTemplatePath+"/contract/simkai.ttf", BaseFont.IDENTITY_H, false);
//创建Font对象,将基础字体对象,字体大小,字体风格
Font font=new Font(bf,13, Font.NORMAL);
int rowNum = 0;
int colNum = 0;
int column=sheet.getColumns();
//下面是找出表格中的空行和空列
List<Integer> nullCol = new ArrayList<>();
List<Integer> nullRow = new ArrayList<>();
for(int j=0;j<sheet.getColumns();j++){
int nullColNum = 0;
for(int i=0;i<sheet.getRows();i++){
Cell cell=sheet.getCell(j, i);
String str = cell.getContents();
if(str == null || "".equals(str)){
nullColNum ++ ;
}
}
if(nullColNum == sheet.getRows()){
nullCol.add(j);
column--;
}
}
for(int i=0;i<sheet.getRows();i++){
int nullRowNum = 0;
for(int j=0;j<sheet.getColumns();j++){
Cell cell=sheet.getCell(j, i);
String str = cell.getContents();
if(str == null || "".equals(str)){
nullRowNum ++ ;
}
}
if(nullRowNum == sheet.getColumns()){
nullRow.add(i);
}
}
PdfPTable table=new PdfPTable(column);
table.setTotalWidth(650);//设置表格的总宽度
//表格多少列,数组就有多长
float[] columnWidth = new float[column];
float tempWidth = 1440/column;
for(int a=0;a<column;a++){
columnWidth[a] = tempWidth;
}
//设置表格的各列宽度
table.setTotalWidth(columnWidth);
table.setLockedWidth(true);
Range[] ranges = sheet.getMergedCells();
PdfPCell cell1=new PdfPCell();
for(int i=0;i<sheet.getRows();i++){
//如果这一行是空行,这跳过这一行
if(nullRow.contains(i)){
continue;
}
for(int j=0;j<sheet.getColumns();j++){
//如果这一列是空列,则跳过这一列
if(nullCol.contains(j)){
continue;
}
boolean flag = true;
Cell cell=sheet.getCell(j, i);
String str = cell.getContents();
//合并的单元格判断和处理
for(Range range : ranges){
if(j >= range.getTopLeft().getColumn() && j <= range.getBottomRight().getColumn()
&& i >= range.getTopLeft().getRow() && i <= range.getBottomRight().getRow()){
if(str == null || "".equals(str)){
flag = false;
break;
}
rowNum = range.getBottomRight().getRow() - range.getTopLeft().getRow()+1;
colNum = range.getBottomRight().getColumn() - range.getTopLeft().getColumn()+1;
if(rowNum > colNum){
cell1 = mergeRow(str, font, rowNum);
cell1.setColspan(colNum);
table.addCell(cell1);
}else {
cell1 = mergeCol(str, font, colNum);
cell1.setRowspan(rowNum);
table.addCell(cell1);
}
flag = false;
break;
}
}
if(flag){
table.addCell(getPDFCell(str,font));
}
}
}
document.add(table);
document.add(new Paragraph("\n\n\n\n\n"));
}
/**
* 合并行的静态函数
* @author myw
* @date 2020年3月19日17:37:32
* @param str
* @param font
* @param i
* @return
*/
public static PdfPCell mergeRow(String str,Font font,int i) {
//创建单元格对象,将内容及字体传入
PdfPCell cell=new PdfPCell(new Paragraph(str,font));
//设置单元格内容居中
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
//将该单元格所在列包括该单元格在内的i行单元格合并为一个单元格
cell.setRowspan(i);
return cell;
}
/**
* 合并列的静态函数
* @author myw
* @date 2020年3月19日17:37:32
* @param str
* @param font
* @param i
* @return
*/
public static PdfPCell mergeCol(String str,Font font,int i) {
PdfPCell cell=new PdfPCell(new Paragraph(str,font));
cell.setMinimumHeight(25);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
//将该单元格所在行包括该单元格在内的i列单元格合并为一个单元格
cell.setColspan(i);
return cell;
}
/**
* 获取指定内容与字体的单元格
* @author myw
* @date 2020年3月19日17:37:32
* @param string
* @param font
* @return
*/
public static PdfPCell getPDFCell(String string, Font font)
{
//创建单元格对象,将内容与字体放入段落中作为单元格内容
PdfPCell cell=new PdfPCell(new Paragraph(string,font));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
//设置最小单元格高度
cell.setMinimumHeight(25);
return cell;
}
/**
* pdf格式数据预览
* @author myw
* @date 2020-3-20 14:7:10
* @param response
* @param path
*/
public static void preview(HttpServletResponse response, String path){
File file = new File(path);
if (file.exists()){
byte[] data = null;
try {
response.setContentType("application/pdf");
FileInputStream input = new FileInputStream(file);
data = new byte[input.available()];
input.read(data);
response.getOutputStream().write(data);
input.close();
} catch (Exception e) {
System.out.println(e);
}
}else{
return;
}
}
}
使用jxl把execl转pdf
最新推荐文章于 2024-06-13 09:59:47 发布