liberoffce生成excel

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了liberoffce生成excel相关的知识,希望对你有一定的参考价值。

参考技术A

Windows下使用LibreOffice将office文档(word,ppt,excel)转成PDF(Java)

第一步:安装Windows版LibreOffice

1.1去官网LibreOffice

https://zh-cn.libreoffice.org/

1.2下载

1.2.1第一步:进入官网点击下载

1.2.2第二步:选择合适自己系统的版本

1.2.2第三步:点击红色框里面的进行下载

1.3安装以及配置

1.3.1第一步:双击下载好的文件

1.3.2第二步:点击下一步

1.3.3第三步:这里选择自定义

1.3.4第四步:这里可以使用默认路劲或者自己选择安装路劲

1.3.5第五步:点击下一步

1.3.6第六步:点击安装

1.3.7第七步:windows10的话找到此电脑=>鼠标右击选择属性=>高级系统设置=>环境变量=>找到系统环境变量path新建添加D:\\LibreOffice\\program路径(注意此路径是根据自己安装的路劲配置的我的是安装在D盘下)

1.3.8第八步然后windows+R打开cmd命令窗口=>输入soffice打开了LibreOffice则表示安装成功

第二步:使用java代码操作LibreOffice进行(doc,ppt,xls)文件转换成PDF文件

1.1:打开IDEA或者eclipse创建一个SpringBoot项目

pom.xml

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.example</groupId>
<artifactId>filepreview</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
</parent>
<dependencies>
<!--Springmvc启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.liumapp.workable.converter</groupId>
<artifactId>workable-converter</artifactId>
<version>v1.4.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build></project>12345678910111213141516171819202122232425262728293031323334353637383940

1.2创建一个类ConvertOfficePDFUtils.java这个文件名称自己取

/**
* @description libreoffice工具类
* @author holle
* @create 2020/12/24
* @since 1.0.0
*/package com.file.preview.utils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Service;import java.io.IOException;import java.io.InputStream;@Servicepublic class ConvertOfficePDFUtils

private static Logger logger=LoggerFactory.getLogger(ConvertOfficePDFUtils.class);

/**
* 利用libreOffice将office文档转换成pdf
* @param inputFile  目标文件地址
* @param pdfFile    输出文件夹
* @return
*/
public static boolean convertOfficePDF(String inputFile,String pdfFile)
long start=System.currentTimeMillis();
String command;
boolean flag;
String osName=System.getProperty("os.name");
if (osName.contains("Windows"))
command="cmd /c start soffice --headless --invisible --convert-to pdf:writer_pdf_Export " + inputFile + " --outdir " + pdfFile;
else
command="libreoffice --headless --invisible --convert-to pdf:writer_pdf_Export " + inputFile + " --outdir " + pdfFile;

flag =executeLibreOfficeCommand(command);
long end =System.currentTimeMillis();
logger.debug("用时: ms", end - start);
return flag;


/**
* 执行command指令
* @param command
* @return
*/
public static boolean executeLibreOfficeCommand(String command)
logger.info("开始进行转化.......");
Process process;// Process可以控制该子进程的执行或获取该子进程的信息
try
logger.debug("convertOffice2PDF cmd : ", command);
process = Runtime.getRuntime().exec(command);// exec()方法指示Java虚拟机创建一个子进程执行指定的可执行程序,并返回与该子进程对应的Process对象实例。
// 下面两个可以获取输入输出流
InputStream errorStream = process.getErrorStream();
InputStream inputStream = process.getInputStream();
catch (IOException e)
logger.error(" convertOffice2PDF error", command,  e);
return false;

int exitStatus = 0;
try
exitStatus = process.waitFor();// 等待子进程完成再往下执行,返回值是子线程执行完毕的返回值,返回0表示正常结束
// 第二种接受返回值的方法
int i = process.exitValue(); // 接收执行完毕的返回值
logger.debug("i----" + i);
catch (InterruptedException e)
logger.error("InterruptedException  convertOffice2PDF ", command, e);
return false;

if (exitStatus != 0)
logger.error("convertOffice2PDF cmd exitStatus ", exitStatus);
else
logger.debug("convertOffice2PDF cmd exitStatus ", exitStatus);

process.destroy(); // 销毁子进程
logger.info("转化结束.......");
return true;
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879

1.3创建一个测试类

/**
* @description 测试类
* @author holle
* @create 2020/12/24
* @since 1.0.0
*/package com.test;import com.file.preview.FilePreviewApplication;import com.file.preview.utils.ConvertOfficePDFUtils;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import javax.annotation.Resource;import java.io.IOException;@RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest(classes = FilePreviewApplication.class)public class TestOffice
@Resource
private ConvertOfficePDFUtils convertOfficePDFUtils;
@Test
public void JunintTestPDF()
long start =System.currentTimeMillis();
String srcPath ="C:/Users/holler/Desktop/*/*.docx",desPath="C:/Users/holler/Desktop/*";
String command="";
String osName=System.getProperty("os.name");
if (osName.contains("Windows"))
//输入cmd命令;添加:srcPath表示文件所在路径;desPath:文件输出的路径
command="soffice --headless --convert-to pdf " + srcPath + " --outdir " + desPath;
convertOfficePDFUtils.executeLibreOfficeCommand(command);

long end=System.currentTimeMillis();
System.out.println("用时: ms"+(end-start));

  1234567891011121314151617181920212223242526272829303132333435363738

Path + " --outdir " + desPath;
convertOfficePDFUtils.executeLibreOfficeCommand(command);

long end=System.currentTimeMillis();
System.out.println(“用时: ms”+(end-start));

Excel--03--读Excel生成java代码

需求:

读此表生成相对应的java代码

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

前端

先省略…

后端编码

public static void main(String[] args) throws Exception {

        //目标表格
        File file = new File("POI\\\\测试.xlsx");
        //生成文件的路径
        String pathDir ="poi\\\\Util.java";


        if(file.exists() && (file.getName().endsWith("xlx")||file.getName().endsWith("xlsx")||file.getName().endsWith("et"))){

            Map<String, List> map = readXls(file);

            writeJava(map,pathDir);

        }

    }

读取Excel文件

Workbook workbook= WorkbookFactory.create(inputStream)


   //读取Excel文件
    public static Map<String,List> readXls (File file) throws Exception{


        Map<String,List> map = new HashMap<>();

        String fileName=file.getName();

        FileInputStream inputStream = new FileInputStream(file);

        Workbook workbook=null;

        if(fileName.endsWith(".xlsx")){
            workbook=new XSSFWorkbook(inputStream);
        }else {
            workbook=new HSSFWorkbook(inputStream);
        }

    //    Workbook workbook= WorkbookFactory.create(inputStream)

        //默认只读表1
        Sheet sheetAt = workbook.getSheetAt(0);
        if(sheetAt == null){
            return map;
        }

        Row rowTitle = sheetAt.getRow(0);
        int countnull =0;

        int firRow=0;
        int laRow=0;

        //获取合并单元格数目
        int sheetmergeCount = sheetAt.getNumMergedRegions();

        for (int i = 0; i < sheetmergeCount; i++) {
            CellRangeAddress range = sheetAt.getMergedRegion(i);
            int firstColumn = range.getFirstColumn();
            int lastColumn = range.getLastColumn();
            int firstRow = range.getFirstRow();
            int lastRow= range.getLastRow();

            if(lastRow <= laRow){
                continue;
            }else {
                //读取此单元格内容,并封装进list
                List list = addList(firstRow, lastRow, sheetAt);
                //获取方法的名字
                String methodName = sheetAt.getRow(firstRow).getCell(1).toString();

                //把这个list数据封装到map里面 ,key是方法的名字,value是list
                if(methodName !=null && !"".equals(methodName) ){
                    map.put(methodName,list);
                }

                if(laRow<=lastRow){
                    firRow=firstRow;
                    laRow=lastRow;
                }
            }

        }
           return map ;
    }

把excel需要的内容输入list

//把excel需要的内容输入list
    public  static List addList(int firstRow, int lastRow, Sheet sheetAt){

        List<String[]> list=new ArrayList<>();

        //读取此单元格的每一行
        for (int rowNum=firstRow ; rowNum<= lastRow; rowNum++){
            Row row = sheetAt.getRow(rowNum);
            if(row ==null){
                continue;
            }


            String[] strArray= new String[10];

            for (int celIX =0 ;celIX<=6; celIX++){

                Cell cell = row.getCell(celIX);

                strArray[celIX]= cell==null ? "" :cell.toString();
            }

            list.add(strArray);

        }

       return  list;
    }


根据读取的Excel信息,写入java文件

  //根据读取的Excel信息写入java
    public static void writeJava(Map map,String targetPath) throws IOException {

        File tarFile = new File(targetPath);
        if(tarFile.exists()){
            tarFile.delete();
        }else {
            tarFile.createNewFile();
        }


        //读取注释模板文件
        // String fileDemoPath= System.getProperty("user.dir")+File.separator+"lib"+File.separator+"Util.txt";
        String fileDemoPath="D:\\\\JavaDevelop\\\\idea_workplace\\\\iodemo\\\\demo.txt";
        String encoding="UTF-8";

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(fileDemoPath), encoding));
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tarFile), encoding));

        String data;
        //拼接类的开头
        while ((data=bufferedReader.readLine())!=null){
            bufferedWriter.write(data);
            bufferedWriter.newLine();
        }

        bufferedWriter.newLine();
        bufferedWriter.newLine();



        Set<String> set = map.keySet();

       //遍历map

        for(String strkey: set){
            String methodName =strkey;

            List<String[]> list =(List)map.get(strkey);

            //写入拼接方法
            writeMethod(methodName,list,bufferedWriter);
            bufferedWriter.newLine();
            bufferedWriter.newLine();
            bufferedWriter.newLine();

        }

        String lastStr="}";
        bufferedWriter.newLine();
        bufferedWriter.write(lastStr);

        bufferedReader.close();
        bufferedWriter.close();
    }

其中模板方法demo.txt ,可以读取 也可以手动拼接

在这里插入图片描述

系统读取的话

System.getProperty(“user.dir”)+File.separator+“lib”+File.separator+“demo.txt”;

写 拼接方法

 //写入拼接方法
    private static Boolean writeMethod(String name, List<String[]> list, BufferedWriter bufferedWriter) throws IOException {
        //生成方法中map的名字
        String mapName =name;
        //方法名
        String methodName ="";

        //方法名首字母大写

        if(mapName !=null && !"".equals(mapName)){
            methodName=mapName.substring(0,1).toUpperCase()+mapName.substring(1);
        }

        if(list.isEmpty()){
            return  false;
        }

        String colum1=list.get(0)[0].toString();
        String colum2=list.get(0)[1].toString();
        String colum3;
        String colum4;
        String colum5;
        String colum6;

        //获取方法的参数 是必输的 为形参
        StringBuilder strArgs = new StringBuilder();
        StringBuilder strArgs2 = new StringBuilder();

        for(String[] strArr:list){
            colum3 =strArr[2].toString();
            colum4 =strArr[3].toString();
            colum5 =strArr[4].toString();
            colum6 =strArr[5].toString();

            if(colum3.contains("[") || colum3.contains("]") ){
                continue;
            }else if(colum6.contains("必")){
                strArgs.append("String ").append(colum3).append(",");
                strArgs2.append(colum3).append("、");
            }
        }

        //去掉strArgs字符串末尾","
        if (strArgs.length()>0){
            strArgs.deleteCharAt(strArgs.length()-1);
        }


        /**
         * 类型 :  渠道要素信息
         * 通讯区名:
         * <p>
         * 必输字段:
         * 需要其他值获取后自行覆盖值
         * </p>
         * @return 返回封装结果集
         */
        bufferedWriter.write("/**");
        bufferedWriter.newLine();
        bufferedWriter.write("* 类型 :" + colum1);
        bufferedWriter.newLine();
        bufferedWriter.write("* 通讯区名:" + colum2);
        bufferedWriter.newLine();
        bufferedWriter.write("* <p>");
        bufferedWriter.newLine();
        bufferedWriter.write("* 必输字段:" + strArgs2);
        bufferedWriter.newLine();
        bufferedWriter.write("* 需要其他值获取后自行覆盖值");
        bufferedWriter.newLine();
        bufferedWriter.write("* <p>");
        bufferedWriter.newLine();
        bufferedWriter.write("* @return 返回封装结果集");
        bufferedWriter.newLine();
        bufferedWriter.write("*/");
        bufferedWriter.newLine();


        String row1="public static Map<String ,Object> "+"get"+methodName+"("+strArgs +"){" ;
        bufferedWriter.write(row1);
        bufferedWriter.newLine();
        String row2="      Map<String ,Object> "+mapName+" = new HashMap<>();";

        bufferedWriter.newLine();
        bufferedWriter.write(row2);
        bufferedWriter.newLine();
        bufferedWriter.newLine();


        //往map里面添加元素
        for(String[] strArr :list){

            StringBuilder str1 = new StringBuilder();
            StringBuilder str2 = new StringBuilder();

            colum3 =strArr[2].toString();
            colum4 =strArr[3].toString();
            colum5 =strArr[4].toString();
            colum6 =strArr[5].toString();

            if(colum3.contains("[") || colum3.contains("]") ){
                continue;
            }else if(colum6.contains("必")){
                str1.append("       //").append(colum5).append(" ").append(colum6);
                str2.append("       ").append(mapName).append(".put(\\"").append(colum3).append("\\",").append(colum3).append(");");

                bufferedWriter.write(str1.toString());
                bufferedWriter.newLine();
                bufferedWriter.write(str2.toString());
                bufferedWriter.newLine();
                bufferedWriter.newLine();


            }else {
                str1.append("       //").append(colum5).append(" ").append(colum6);
                str2.append("       ").append(mapName).append(".put(\\"").append(colum3).append("\\",").append(" \\"\\");");

                bufferedWriter.write(str1.toString());
                bufferedWriter.newLine();
                bufferedWriter.write(str2.toString());
                bufferedWriter.newLine();
                bufferedWriter.newLine();
            
        }

        String strReturn ="       return "+mapName+" ;";
        String lasrStr="}";

        bufferedWriter.write(strReturn);
        bufferedWriter.newLine();
        bufferedWriter.write(lasrStr);
        
        return true;
        }

以上是关于liberoffce生成excel的主要内容,如果未能解决你的问题,请参考以下文章

excel如何生成按日期命名的表

POI动态生成Excel

java怎么生成excel柱状图

怎样在EXCEL中自动生成拼音

在excel表中输入商品名称怎样自动生成商品编码

如何实现excel数据导入批量生成二维码