java使用POI实现替换文件中指定关键字

来源:互联网 发布:淘宝好吃的泡面排行榜 编辑:程序博客网 时间:2024/05/21 09:29

有时候需要将文件中的某些关键字替换成新的关键字,而文件可能是不同类型的,笔者曾经就面临这种需求。

Apache POI是一种流行的API,它允许程序员使用Java程序创建,修改和显示MS Office文件。这是Apache软件基金会开发的,使用Java分布式设计,可修改Microsoft Office文件的开源库。
由于需求比较简单,所以没有使用springMVC,而采用简单的JSP与Servlet。

项目需要导入的包如下:
这里写图片描述
src代码结构如下:
这里写图片描述
UploadServlet为文件上传的sevlet,DownloadServlet为文件下载的sevlet。DocStringReplace,TexStringReplace, ExcelStringReplace,
PPTStringReplace分别为处理.doc, .txt ,.xls ,.xlsx *,.pptx类型的文件。
upload.jsp为欢迎界面:
这里写图片描述
选择文件后,设置目标关键词与新关键词,点击上传,结果界面如下:
这里写图片描述
出现上图界面表示关键词替换成功,点击下载可以将处理后的新文件下载到客户端。

upload.jsp代码如下:

<%@ page contentType="text/html; charset=UTF-8" language="java" errorPage="" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head>    <title> 文件上传 </title>    <style type="text/css">    body{        padding-top:100px;        text-align:center;    }    </style></head><body><div id="doc" ><div>选择文件类型可以是:*.txt *.doc *.xls *.xlsx *.pptx</div><br/><div>生成的新文件在服务器,上传完成后,请立即下载,下载完成后服务器将清除该文件</div><br/><form method="post" action="upload"  enctype="multipart/form-data">原关键字:<input type="text" id="target" name="target" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;新关键字:<input type="text" id="newContent" name="newContent" /><br/>    选择文件:<input type="file" id="file" name="file" /><br/>    <input type="submit" value="上传" /><br/></form></div></body></html>

UploadServlet代码如下:

import java.io.IOException;import java.io.PrintWriter;import java.util.HashMap;import java.util.Map;import javax.servlet.ServletException;import javax.servlet.annotation.MultipartConfig;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.Part;@SuppressWarnings("serial")@WebServlet("/upload") @MultipartConfigpublic class UploadServlet extends HttpServlet{    public void service(HttpServletRequest request ,        HttpServletResponse response)        throws IOException , ServletException    {        response.setContentType("text/html;charset=UTF-8");        PrintWriter out = response.getWriter();        request.setCharacterEncoding("UTF-8");        // 获取target请求参数        String target = request.getParameter("target");        // 获取newContent请求参数        String newContent = request.getParameter("newContent");        // 获取文件上传域        Part part = request.getPart("file");        String fileNameInfo = part.getHeader("content-disposition");        // 提取上传文件的原始文件名        String fileName = fileNameInfo.substring(            fileNameInfo.indexOf("filename=\"") + 10 , fileNameInfo.length() - 1);        // 将上传的文件写入服务器        String fileNameN = fileName.substring(0,fileName.lastIndexOf(".")) + System.currentTimeMillis() + "." + fileName.substring(fileName.lastIndexOf("."), fileName.length());         String filePath = getServletContext().getRealPath("/uploadFiles") + "\\" + fileNameN;        System.out.println(filePath);        part.write(filePath);           boolean isSuccess = processStringReplace(filePath, target, newContent);        if(isSuccess){        out.println("关键字替换成功!" + "<br/>");        // 获取上传文件的文件类型        out.println("上传文件的的类型为:" + part.getContentType() + "<br/>");        //获取上传文件的大小        out.println("上传文件的的大小为:" + part.getSize()  + "<br/>");        // 获取包含原始文件名的字符串        out.println("上传的文件名为:" + fileName + "<br/>");        out.println("新文件名: " + fileNameN );        out.println("<a href='download?fileName=" + fileNameN+" '>下载</a>");        }else{            out.println("关键字替换出错!请检查文件类型或者联系开发者!" + "<br/>");        }    }    /**     * @param filePath是文件路径,文件放在test文件夹下面     * @param target是要替换的目标字符串(关键字),newContent是用来替换目标的新字符串     */private  boolean processStringReplace(String filePath, String target, String newContent) {    boolean isSuccess = false;     switch(getFileType(filePath)){     case "txt":         isSuccess = TxtStringReplace.replaceStringIntxt(filePath, target, newContent);         break;     case "doc":         Map<String, String> map=new HashMap<String, String>();           map.put(target, newContent);          isSuccess = DocStringReplace.replaceStringInDoc(filePath, map);         break;     case "xls":         Map<String,String> mapXls = new HashMap<String,String>();           mapXls.put(target,newContent);           isSuccess = ExcelStringReplace.replaceStringInExcel(filePath, mapXls);         break;     case "xlsx":         Map<String,String> mapXlsx = new HashMap<String,String>();           mapXlsx.put(target,newContent);           isSuccess = ExcelStringReplace.replaceStringInExcel(filePath, mapXlsx);         break;     case "pptx":         isSuccess = PPTStringReplace.replaceStringInPPT(filePath, target, newContent);         break;     default:         System.out.println("please use documents like *.txt *.doc *.xls *.xlsx *.pptx");         isSuccess = false;         break;     }     return isSuccess;}public String getFileType(String fileName) {    String[] strArray = fileName.split("\\.");    int suffixIndex = strArray.length -1;    return strArray[suffixIndex];        }}

以下分别是.doc, .txt ,.xls ,.xlsx *,.pptx类型文件的处理类:

public class DocStringReplace {    public static boolean replaceStringInDoc(String filePath,Map<String, String> map) {          boolean isSuccess = true;        try {              FileInputStream in = new FileInputStream(new File(filePath));              HWPFDocument hdt = new HWPFDocument(in);              Range range = hdt.getRange();              //替换文本内容              for (Map.Entry<String,String> entry:map.entrySet()) {                  range.replaceText(entry.getKey(),entry.getValue());              }              ByteArrayOutputStream ostream = new ByteArrayOutputStream();              FileOutputStream out = new FileOutputStream(filePath);              hdt.write(ostream);              //输出字节流              out.write(ostream.toByteArray());              ostream.close();              out.close();            System.out.println("doc replace success");        } catch (Exception e) {            isSuccess = false;            e.printStackTrace();         }        return isSuccess;    }  }
public class TxtStringReplace {    public static boolean replaceStringIntxt(String filePath,String target,String newContent){        boolean isSuccess = true;        try{            // 读              File file = new File(filePath);               FileReader in = new FileReader(file);              BufferedReader bufIn = new BufferedReader(in);              // 内存流, 作为临时流              CharArrayWriter  tempStream = new CharArrayWriter();              // 替换              String line = null;              while ( (line = bufIn.readLine()) != null) {                  // 替换每行中, 符合条件的字符串                  line = line.replaceAll(target, newContent);                // 将该行写入内存                  tempStream.write(line);                  // 添加换行符                  tempStream.append(System.getProperty("line.separator"));                  }                  // 关闭 输入流                  bufIn.close();                  // 将内存中的流 写入 文件                  FileWriter out = new FileWriter(file);                  tempStream.writeTo(out);                  out.close();                 System.out.println("txt replace success");        }catch(IOException ex){            isSuccess = false;            ex.printStackTrace();        }        return isSuccess;    }}
public class ExcelStringReplace {    public static boolean replaceStringInExcel(String filePath, Map<String,String> item) {          boolean isSuccess = true;          Workbook wb =null;        try {              if(getFileType(filePath).equals("xls")){                System.out.print("xls ");                POIFSFileSystem fs  =new POIFSFileSystem(new FileInputStream(filePath));                wb = new HSSFWorkbook(fs);                processHSSFWorkbook(wb, item);            }else if(getFileType(filePath).equals("xlsx")){                System.out.print("xlsx ");                FileInputStream input = new FileInputStream(new File(filePath));                wb = new XSSFWorkbook(OPCPackage.open(input));                processXSSFWorkbook(wb, item);            }            // 输出文件              FileOutputStream fileOut = new FileOutputStream(filePath);              wb.write(fileOut);              fileOut.close();              wb.close();            System.out.println("replace success");        } catch (Exception e) {              isSuccess = false;              e.printStackTrace();          }          return isSuccess;      }      public static String getFileType(String fileName) {        String[] strArray = fileName.split("\\.");        int suffixIndex = strArray.length -1;        return strArray[suffixIndex];            }    /****处理Excel2003****/    public static void processHSSFWorkbook(Workbook wb,Map<String,String> item){        HSSFSheet sheet = (HSSFSheet) wb.getSheetAt(0);          Iterator<?> rows = sheet.rowIterator();          while(rows.hasNext()){                 HSSFRow row = (HSSFRow) rows.next();            if(row!=null)            {                  int num = row.getLastCellNum();                for(int i=0;i<num;i++)                {                    HSSFCell cell=  row.getCell(i);                    if(cell!=null)                    {                      cell.setCellType(XSSFCell.CELL_TYPE_STRING);                    }                    if(cell==null || cell.getStringCellValue()==null)                    {                        continue;                    }                     String value= cell.getStringCellValue();                    if(!"".equals(value))                    {                      Set<String> keySet = item.keySet();                      Iterator<String> it = keySet.iterator();                      while (it.hasNext()) {                          String text = it.next();                          if(value.equals(text))                          {                              cell.setCellValue((String)item.get(text));                              break;                          }                      }                    }else{                        cell.setCellValue("");                    }                }            }            }      }    /****处理Excel2007+****/    private static void processXSSFWorkbook(Workbook wb, Map<String, String> item) {        XSSFSheet sheet = (XSSFSheet) wb.getSheetAt(0);          Iterator<?> rows = sheet.rowIterator();          while(rows.hasNext()){                 XSSFRow row = (XSSFRow) rows.next();            if(row!=null)            {                  int num = row.getLastCellNum();                for(int i=0;i<num;i++)                {                    XSSFCell cell=  row.getCell(i);                    if(cell!=null)                    {                      cell.setCellType(XSSFCell.CELL_TYPE_STRING);                    }                    if(cell==null || cell.getStringCellValue()==null)                    {                        continue;                    }                     String value= cell.getStringCellValue();                    if(!"".equals(value))                    {                      Set<String> keySet = item.keySet();                      Iterator<String> it = keySet.iterator();                      while (it.hasNext()) {                          String text = it.next();                          if(value.equals(text))                          {                              cell.setCellValue((String)item.get(text));                              break;                          }                      }                    }else{                        cell.setCellValue("");                    }                }            }            }      }}
public class PPTStringReplace {    public static boolean replaceStringInPPT(String filePath,String target,String newContent){        boolean isSuccess = true;        try{            //获取ppt文件             FileInputStream is = new FileInputStream(filePath);             XMLSlideShow ppt = new XMLSlideShow(is);             is.close();             // 获取幻灯片             for (XSLFSlide slide : ppt.getSlides()) {                 // 获取每一张幻灯片中的shape                 for (XSLFShape shape : slide.getShapes()) {                     if (shape instanceof XSLFTextShape) {                         XSLFTextShape txShape = (XSLFTextShape) shape;                             // 替换文字内容                             txShape.setText(txShape.getText().replace(target,newContent));                     } else if (shape instanceof XSLFGroupShape) {                         for (XSLFShape sunshape : ((XSLFGroupShape) shape).getShapes()) {                             XSLFTextShape txSunShape = (XSLFTextShape) sunshape;                                 // 替换文字内容                                 txSunShape.setText(txSunShape.getText().replace(target, newContent));                         }                     }                  }             }             FileOutputStream out = new FileOutputStream(filePath);             ppt.write(out);             out.close();             ppt.close();             System.out.println("ppt replace success");        }catch(IOException ex){            isSuccess = false;            ex.printStackTrace();        }        return isSuccess;    }}

以下是DownloadServlet的代码:

import java.io.FileInputStream;  import java.io.IOException;  import java.io.InputStream;  import java.io.OutputStream;  import java.net.URLEncoder;  import javax.servlet.ServletException;  import javax.servlet.annotation.WebServlet;  import javax.servlet.http.HttpServlet;  import javax.servlet.http.HttpServletRequest;  import javax.servlet.http.HttpServletResponse;  @WebServlet("/download")  public class DownloadServlet extends HttpServlet {      private static final long serialVersionUID = 1L;      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {          response.setContentType("application/x-msdownload");           request.setCharacterEncoding("UTF-8");        String fileName = request.getParameter("fileName");          response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));          OutputStream out = response.getOutputStream();          String pptFileName = getServletContext().getRealPath("/uploadFiles") + "\\"+fileName;           InputStream in = new FileInputStream(pptFileName);          byte [] buffer = new byte[1024];          int len = 0;          while((len = in.read(buffer)) != -1){              out.write(buffer, 0, len);          }          in.close();      }  }  

项目只考虑到部分情况,所以对于有些文件可能不适用。

阅读全文
1 0
原创粉丝点击