Java比较两个文本的区别,同一单元格不同颜色标在Excel上

 1、递归算法比较两个文本的区别,并用标签标出(下面excel是用@@分开  所以标签要改成@@)。

//递归算法
public class StringCompareTest2 {
	
	public static void main(String[] args) {
		
		String[] hd = getHighLightDifferent("你好宽带", "你好");
		
		for(String s:hd){
			System.out.println(s);
		}
		
	}
	
	
	public static String[] getHighLightDifferent(String a,String b){
		String[] temp=getDiff(a, b);
		String[] result={getHighLight(a, temp[0]),getHighLight(b, temp[1])};
		return result;
	}
	
	private static String getHighLight(String source,String temp){
		StringBuffer sb=new StringBuffer();
		char[] sourceChars=source.toCharArray();
		char[] tempChars=temp.toCharArray();
		boolean flag=false;
		for(int i=0;i<sourceChars.length;i++){
			if(tempChars[i]!=' '){
				if(i==0) sb.append("<span style='color:blue'>").append(sourceChars[i]);//append@@
				else if(flag) sb.append(sourceChars[i]);
				else sb.append("<span style='color:blue'>").append(sourceChars[i]);//append@@
				flag=true;
				if(i==sourceChars.length-1) sb.append("</span>");//append@@
			}
			else if(flag==true){
				sb.append("</span>").append(sourceChars[i]);//append@@
				flag=false;
			}else sb.append(sourceChars[i]);
		}
		return sb.toString();
	}
	public static String[] getDiff(String a, String b) {
        String[] result = null;
        //选取长度较小的字符串用来穷举子串
        if (a.length() < b.length()) {
            result = getDiff(a, b, 0, a.length());
        } else {
            result = getDiff(b, a, 0, b.length());
            result = new String[]{result[1],result[0]};
        }
        return result;
    }
 
    private static String[] getDiff(String a, String b, int start, int end){
        String[] result = new String[]{a, b};
        int len = result[0].length();
        while (len > 0) {
            for (int i = start; i < end - len + 1; i++) {
                String sub = result[0].substring(i, i + len);
                int idx = -1;
                if ((idx = result[1].indexOf(sub)) != -1) {
                    result[0] = setEmpty(result[0], i, i + len);
                    result[1] = setEmpty(result[1], idx, idx + len);
                    if (i > 0) {
                        //递归获取空白区域左边差异
                        result = getDiff(result[0], result[1], 0, i);
                    }
                    if (i + len < end) {
                        //递归获取空白区域右边差异
                        result = getDiff(result[0], result[1], i + len, end);
                    }
                    len=0;//退出while循环
                    break;
                }
            }
            len = len / 2;
        }
        return result;
    }
 
    //将字符串s指定的区域设置成空格
    public static String setEmpty(String s, int start, int end) {
        char[] array = s.toCharArray();
        for (int i = start; i < end; i++) {
            array[i] = ' ';
        }
        return new String(array);
    }
}

 

2、同一单元格不同颜色标在Excel上


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPalette;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Workbook;

/**
 * 导出Excel公共方法
 *
 */
public class ExcelDiffUtil{
    
    //显示的导出表的标题
    private String title;
    //导出表的列名
    private String[] rowName ;
    
    private List<Object[]>  dataList = new ArrayList<Object[]>();
    
    HttpServletResponse  response;
    
    //构造方法,传入要导出的数据
    public ExcelDiffUtil(String title,String[] rowName,List<Object[]>  dataList){
        this.dataList = dataList;
        this.rowName = rowName;
        this.title = title;
    }
            
    /*
     * 导出数据
     * */
    public Workbook export() throws Exception{
    	 HSSFWorkbook workbook = new HSSFWorkbook();    
    	 try{
                               // 创建工作簿对象
            HSSFSheet sheet = workbook.createSheet(title);                     // 创建工作表
            
            HSSFFont font = workbook.createFont();
			font.setFontHeightInPoints((short) 24); // 字体高度
			font.setFontName("宋体"); // 字体
			font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 宽度
 
			HSSFFont font1=getColor(workbook,"#3366FF");
			
			 HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);//获取列头样式对象
	            HSSFCellStyle style = this.getStyle(workbook);  
            
            // 定义所需列数
            int columnNum = rowName.length;
            HSSFRow rowRowName = sheet.createRow(0);                // 在索引2的位置创建行(最顶端的行开始的第二行)
            
            rowRowName.setHeight((short) (25 * 25)); //设置高度
            
            // 将列头设置到sheet的单元格中
            for(int n=0;n<columnNum;n++){
                HSSFCell  cellRowName = rowRowName.createCell(n);                //创建列头对应个数的单元格
                cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING);                //设置列头单元格的数据类型
                HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
                cellRowName.setCellValue(text);                                    //设置列头单元格的值
                cellRowName.setCellStyle(columnTopStyle);                        //设置列头单元格样式
            }
            
            //将查询出的数据设置到sheet对应的单元格中
            for(int i=0;i<dataList.size();i++){
                
                Object[] obj = dataList.get(i);//遍历每个对象
                HSSFRow row = sheet.createRow(i+1);//创建所需的行数     没有第一行就+1
                
                row.setHeight((short) (25 * 20)); //设置高度
                
                for(int j=0; j<obj.length; j++){
                    HSSFCell  cell = null;   //设置单元格的数据类型
                    
                    /**
                     * 
                     * 
                     * 第一列
                     * 
                     */
                    if(j == 0){
                        cell = row.createCell(j,HSSFCell.CELL_TYPE_NUMERIC);
                        //cell.setCellValue(i+1);    
                        if(!"".equals(obj[j]) && obj[j] != null){
                            cell.setCellValue(obj[j].toString());                        //设置单元格的值
                        }
                    }else{
                        cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING);
                        
                        String str=obj[j].toString();
                        if(!"".equals(str) && str != null){
                        	 /**
                             * FIXME
                             * 同一个单元格  不同的字体格式  颜色
                             */
                        	
                        	List<Map<String,Integer>> tsList;
                        	Map<String,Integer> map;
                        	int start;
                        	if(str.contains("@@")){
                        		tsList=new ArrayList<Map<String,Integer>>();
                        		String[] strings = str.split("@@");//工作一定要@@认真,态度要端正@@,作风要@@优@@良,行事要效率,力争@@打造一个@@完美的产品出来。
                        		for(int k=0;k<strings.length;k++){
                        			if(k%2==1){
                        				map=new HashMap();
                        				start=0;
                        				for(int l=0;l<k;l++){
                        					start+=strings[l].length();
                        				}
                        				map.put("start", start);
                            			map.put("end", start+strings[k].length());
                            			tsList.add(map);
                        			}
                        		}
                        		
	                        	HSSFRichTextString ts= new HSSFRichTextString(obj[j].toString().replace("@@", ""));
	                        	for(Map m:tsList){
	                        		ts.applyFont(Integer.parseInt(m.get("start").toString()),Integer.parseInt(m.get("end").toString()),font1);
	                        	}	
	                        		
	                        	cell.setCellValue(ts);
                        		
                        		
                        	}else{
                        		cell.setCellValue(str); 
                        	}
                        	
                        	
                        }
                    }
                }
            }
            //让列宽随着导出的列长自动适应
            for (int colNum = 0; colNum < columnNum; colNum++) {
                int columnWidth = sheet.getColumnWidth(colNum) / 256;
                for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                    HSSFRow currentRow;
                    //当前行未被使用过
                    if (sheet.getRow(rowNum) == null) {
                        currentRow = sheet.createRow(rowNum);
                    } else {
                        currentRow = sheet.getRow(rowNum);
                    }
                    if (currentRow.getCell(colNum) != null) {
                        HSSFCell currentCell = currentRow.getCell(colNum);
                        if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                            int length = currentCell.getStringCellValue().getBytes().length;
                            if (columnWidth < length) {
                                columnWidth = length;
                            }
                        }
                    }
                }
                if(colNum == 0){
                    sheet.setColumnWidth(colNum, (columnWidth-2) * 128);
                }else{
                    sheet.setColumnWidth(colNum, (columnWidth+4) * 256);
                }
                
            }

        }catch(Exception e){
            e.printStackTrace();
        }
        return workbook;
    }
    
    
    
    public void printExcel(Workbook workbook){
    	 if(workbook !=null){
             try
             {
             	File file=new File("D:\\data\\" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()).toString() +".xls");
                 file.createNewFile();
             	FileOutputStream out = new FileOutputStream(file);
                 workbook.write(out);
                 out.close();
             }
             catch (IOException e)
             {
                 e.printStackTrace();
             }
         }
    	
    	
    }
    
    /* 
     * 列头单元格样式
     */    
      public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {
          
            // 设置字体
          HSSFFont font = workbook.createFont();
          //设置字体大小
          font.setFontHeightInPoints((short)11);
          //字体加粗
          font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
          //设置字体名字 
          font.setFontName("Courier New");
          //设置样式; 
          HSSFCellStyle style = workbook.createCellStyle();
          //设置底边框; 
          style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
          //设置底边框颜色;  
          style.setBottomBorderColor(HSSFColor.BLACK.index);
          //设置左边框;   
          style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
          //设置左边框颜色; 
          style.setLeftBorderColor(HSSFColor.BLACK.index);
          //设置右边框; 
          style.setBorderRight(HSSFCellStyle.BORDER_THIN);
          //设置右边框颜色; 
          style.setRightBorderColor(HSSFColor.BLACK.index);
          //设置顶边框; 
          style.setBorderTop(HSSFCellStyle.BORDER_THIN);
          //设置顶边框颜色;  
          style.setTopBorderColor(HSSFColor.BLACK.index);
          //在样式用应用设置的字体;  
          style.setFont(font);
          //设置自动换行; 
          style.setWrapText(false);
          //设置水平对齐的样式为居中对齐;  
          style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
          //设置垂直对齐的样式为居中对齐; 
          style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
          
          //设置单元格背景颜色
          style.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
          style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
          
          return style;
          
      }
      
      /*  
     * 列数据信息单元格样式
     */  
      public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
            // 设置字体
            HSSFFont font = workbook.createFont();
            //设置字体大小
            //font.setFontHeightInPoints((short)10);
            //字体加粗
            //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            //设置字体名字 
            font.setFontName("Courier New");
            //设置样式; 
            HSSFCellStyle style = workbook.createCellStyle();
            //设置底边框; 
            style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            //设置底边框颜色;  
            style.setBottomBorderColor(HSSFColor.BLACK.index);
            //设置左边框;   
            style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            //设置左边框颜色; 
            style.setLeftBorderColor(HSSFColor.BLACK.index);
            //设置右边框; 
            style.setBorderRight(HSSFCellStyle.BORDER_THIN);
            //设置右边框颜色; 
            style.setRightBorderColor(HSSFColor.BLACK.index);
            //设置顶边框; 
            style.setBorderTop(HSSFCellStyle.BORDER_THIN);
            //设置顶边框颜色;  
            style.setTopBorderColor(HSSFColor.BLACK.index);
            //在样式用应用设置的字体;  
            style.setFont(font);
            //设置自动换行; 
            style.setWrapText(false);
            //设置水平对齐的样式为居中对齐;  
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            //设置垂直对齐的样式为居中对齐; 
            style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
           
            return style;
      }
      
      /**
       * 自定义颜色
       * @param workbook
       * @param str
       * @return
       */
      public HSSFFont getColor(HSSFWorkbook workbook,String str) {
	      //String str = "#3366FF";
		  //处理把它转换成十六进制并放入一个数
		  int[] color=new int[3];
	      color[0]=Integer.parseInt(str.substring(1, 3), 16);
	      color[1]=Integer.parseInt(str.substring(3, 5), 16);
	      color[2]=Integer.parseInt(str.substring(5, 7), 16);
	     //自定义颜色
	      HSSFPalette palette = workbook.getCustomPalette();
	      palette.setColorAtIndex(HSSFColor.BLACK.index,(byte)color[0], (byte)color[1], (byte)color[2]);
	      //将自定义的颜色引入进来
	      HSSFFont font=workbook.createFont();
	      font.setColor(HSSFColor.BLACK.index);
	      return font;
      }
      
      
      
      public static void main(String[] args) throws Exception {
          List<HashMap<String, Object>> listMap = new ArrayList<>();
          HashMap<String,Object> dataMap = new HashMap<>();
          
          for(int i=0;i<30;i++){
              dataMap.put("type", "文本");
              dataMap.put("content", "工作一定要@@认真,态度要端正@@,作风要@@优@@良,行事要效率,力争@@打造一个@@完美的产品出来。");
              listMap.add(dataMap);
          }
          
          String title = "测试";
          String[] rowsName = new String[]{"类型","消息"};
          List<Object[]>  dataList = new ArrayList<Object[]>();
          Object[] objs = null;
          for (int i = 0; i < listMap.size(); i++) {
              HashMap<String, Object> data = listMap.get(i);
              objs = new Object[rowsName.length];
              objs[0] = data.get("type");
              objs[1] = data.get("content");
              dataList.add(objs);
          }
          ExcelDiffUtil ex = new ExcelDiffUtil(title, rowsName, dataList);
          ex.printExcel(ex.export());
      }
}

用@@围住的文本是不同颜色显示的;

第一段代码中使用<span>标签围的,所以替换一下就好了

第二段代码在服务器上生成workbook后,可以用以下downloadExcel方法下载:

package com.zjpii.wanbao.console.util;

import java.beans.PropertyDescriptor;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import cn.zj.pubinfo.comm.core.exception.BaseException;

public class ExcelUtil {
	/**
	 * 得到Workbook对象
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public static Workbook getWorkBook(MultipartFile file) throws IOException{
		//这样写  excel 能兼容03和07
		InputStream is = file.getInputStream();
		Workbook hssfWorkbook = null; 
		try { 
		    hssfWorkbook = new HSSFWorkbook(is); 
		} catch (Exception ex) {
		    is =file.getInputStream();
		    hssfWorkbook = new XSSFWorkbook(is); 
		}
		return hssfWorkbook;
	}
	
	/**
	 * 得到错误信息
	 * @param sb
	 * @param list
	 * @param i
	 * @param obj
	 * @param name  用哪个属性名去表明不和规定的数据
	 * @param msg
	 * @throws Exception
	 */
	public static void getWrongInfo(StringBuilder sb,List list,int i,Object obj,String name,String msg) throws Exception{
		Class clazz=obj.getClass();
		Object str=null;
		//得到属性名数组 
		Field[] fields = clazz.getDeclaredFields();
		 for(Field f : fields){
			 if(f.getName().equals(name)){
				 //用来得到属性的get和set方法
				 PropertyDescriptor pd = new PropertyDescriptor(f.getName(), clazz);
				 //得到get方法
				 Method getMethod=pd.getReadMethod();
				 str = getMethod.invoke(obj);
			 }
		 }
		 if(i==0)
				sb.append(msg+str+";");
		 else if(i==(list.size()-1))
				sb.append(str+"</br>");
		 else
				sb.append(str+";");
	}
	/**
	 * 
	 * @param response
	 * @param wb
	 * @param showFileName
	 * @throws IOException
	 */
	public static void downloadExcel(HttpServletResponse response, Workbook wb, String showFileName) throws IOException {
		 // 判断数据
        if(wb == null) {
        	throw new BaseException(50001000);
        }
        // 重置响应对象
        response.reset();
        // 当前日期,用于导出文件名称
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = showFileName+sdf.format(new Date())+".xls";
        // 指定下载的文件名--设置响应头
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(dateStr.getBytes("gb2312"), "ISO8859-1"));
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        // 写出数据输出流到页面
        try {
            OutputStream output = response.getOutputStream();
            BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
            wb.write(bufferedOutPut);
            bufferedOutPut.flush();
            bufferedOutPut.close();
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值