`
renjie120
  • 浏览: 234922 次
  • 性别: Icon_minigender_1
  • 来自: 上海
博客专栏
D11bba82-ec4a-3d31-a3c0-c51130c62f1c
Java应用集锦
浏览量:22457
社区版块
存档分类
最新评论

java应用集锦3:正则表达式 excel操作之jxl

    博客分类:
  • java
阅读更多

转载请注明出处: http://renjie120.iteye.com/

 

最近项目开发中对excel操作比较频繁,并结合正则表达式进行了一些处理,整理一下.


 

1.正则表达式常用方法

/**
	 * 在第一个字符串中查找匹配字符串的个数
	 * @param str  
	 * @param regexStr
	 * @return
	 */
	public static int count(String str,String regexStr){
		int count = 0;
		Pattern pt = Pattern.compile(regexStr);
		Matcher m = pt.matcher(str);
		int start = 0;
		while(m.find()){
			count++;
		}
		return count;
	}

/**
	 * 根据正则表达式分割str字符串成为一个一个的小的单元!
         * (实际使用:在一个类似语法分析的模块中发挥重要作用)
	 * 例如:3+5*4  根据正则表达式+-\*  分割成数组  3,+,5,*,4  
	 * @param str
	 * @param regexStr
	 * @return
	 */
	public static List splitByStr(String str,String regexStr){
		List temp = new ArrayList();
		Pattern pt = Pattern.compile(regexStr);
		Matcher m = pt.matcher(str);
		int start = 0;
		while(m.find()){
			//去掉下面的字符串中为空串的情况!
			if(m.start()!=start)
				temp.add(str.substring(start, m.start()));
			temp.add(str.substring(m.start(),m.end()));
			start = m.end();
		}
		temp.add(str.substring(start));
		return temp;
	}

      /**
	 * 检查是否含有指定的正则表达式匹配的子串.
	 * @param str 目标字符串
	 * @param regex 正则表达式,如果正则表达式含有"^......$"就是查找整个字符串对象是否符合正则表达式.
	 * @return
	 */
	public static boolean checkInclude(String str,String regex){
		 Pattern pattern = Pattern.compile(regex);
         Matcher matcher = null;
         matcher = pattern.matcher(str);
         return matcher.find();
	}
		
	/**
	 * 方法字符串中符合正则表达式的子串的集合.
	 * @param str
	 * @param regex
	 * @return
	 */
	public static List getRightSubStr(String str, String regex) {
		List ans = new ArrayList();
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(str);
		while (matcher.find()) {
			//注意要下面的goup()函数中可以含有数字,表示查找得到正则表达式中的goup匹配串.
			ans.add(matcher.group());
			System.out.println("找到匹配的字符串 \"" + matcher.group()
					+ "\" 开始于 " + matcher.start()
					+ " 结束于 " + matcher.end() + ".");
		}
		return ans;
	}

 下面是java正则表达式经常使用的一些方法和说明:

(1)使用matches方法快速建设是否表示给定的输入字符串:Pattern.matches("\\d","1")返回true
(2)split(string)使用方法:Pattern.compile(":").split("one:two:three:four:five");  返回:解析出“one two three four five”单词
再比如使用数字作为一个分割字符串的方法:(注意下面的\\d不是正则表达式,而是前面加了一个转义符号\)
Pattern.compile("\\d").split("one9two4three7four1five");也返回相同的结果。。
(3)在String类中有的几个与Pattern类似的方法:
public boolean matches(String regex):
public String[] split(String regex, int limit):
public String[] split(String regex):
public String replace(CharSequence target,CharSequence replacement):
(4) Matcher 类中其他一些有用的方法
索引方法
  索引方法(index methods)提供了一些正好在输入字符串中发现匹配的索引值:
  public int start():返回之前匹配的开始索引。
  public int start(int group):返回之前匹配操作中通过给定组所捕获序列的开始索引。
  public int end(): 返回最后匹配字符后的偏移量。
  public int end(int group): 返回之前匹配操作中通过给定组所捕获序列的最后字符之后的偏移量。 
研究方法
  研究方法(study methods)回顾输入的字符串,并且返回一个用于指示是否找到模式的布尔值。
  public boolean lookingAt(): 尝试从区域开头处开始,输入序列与该模式匹配。
  public boolean find(): 尝试地寻找输入序列中,匹配模式的下一个子序列。
  public boolean find(int start): 重置匹配器,然后从指定的索引处开始,尝试地寻找输入序列中,匹配模式的下一个子序列。
  public boolean matches(): 尝试将整个区域与模式进行匹配 
替换方法
  替换方法(replacement methods)用于在输入的字符串中替换文本有用处的方法。
  public Matcher appendReplacement(StringBuffer sb, String replacement):实现非结尾处的增加和替换操作。
  public StringBuffer appendTail(StringBuffer sb):实现结尾处的增加和替换操作。
  public String replaceAll(String replacement):使用给定的替换字符串来替换输入序列中匹配模式的每一个子序列。
  public String replaceFirst(String replacement):使用给定的替换字符串来替换输入序列中匹配模式的第一个子序列。
  public static String quoteReplacement(String s):返回指定字符串的字面值来替换字符串。这个方法会生成一个字符串,用作 Matcher 的 appendReplacement 方法中的字面值替换 s。所产生的字符串将与作为字面值序列的 s 中的字符序列匹配。斜线(\)和美元符号($)将不再有特殊意义了。 

   正则表达式基础:

字符类
[abc]   a, b 或 c(简单类)
[^abc]         除 a, b 或 c 之外的任意字符(取反)
[a-zA-Z]           a 到 z,或 A 到 Z,包括(范围)
[a-d[m-p]]              a 到 d,或 m 到 p---等价于[a-dm-p](并集) (特别注意这里的并集的方式啊,很特别!!)
[a-z&&[def]]               d,e 或 f(交集)
[a-z&&[^bc]]              除 b 和 c 之外的 a 到 z 字符等价于[ad-z](差集)
[a-z&&[^m-p]]                     a 到 z,并且不包括 m 到 p等价于[a-lq-z](差集)

 

预定义字符类
.         任何字符(匹配或者不匹配行结束符)
\d         数字字符:[0-9]
\t        tab键
\D         非数字字符:[^0-9]
\s         空白字符:[\t\n\x0B\f\r]
\S         非空白字符:[^\s]
\w         单词字符:[a-zA-Z_0-9]
\W         非单词字符:[^\w]

 

边界匹配器
^         行首
$         行尾
\b         单词边界
\B         非单词边界
\A         输入的开头
\G         上一个匹配的结尾
\Z         输入的结尾,仅用于最后的结束符(如果有的话)
\z         输入的结尾

 2.使用jxl进行exlce的基本操作

下面基础代码来自于网络:

import java.io.File;  
import java.io.FileOutputStream;  
import java.io.OutputStream;  
import java.util.ArrayList;  
import java.util.Date;  
 
import jxl.Cell;  
import jxl.CellType;  
import jxl.Sheet;  
import jxl.Workbook;  
import jxl.WorkbookSettings;  
import jxl.format.Alignment;  
import jxl.format.Border;  
import jxl.format.BorderLineStyle;  
import jxl.format.Colour;  
import jxl.format.VerticalAlignment;  
import jxl.write.Formula;  
import jxl.write.Label;  
import jxl.write.NumberFormat;  
import jxl.write.WritableCellFeatures;  
import jxl.write.WritableCellFormat;  
import jxl.write.WritableFont;  
import jxl.write.WritableSheet;  
import jxl.write.WritableWorkbook;  
import jxl.write.WriteException;  
 
public class JExcelUtils {  
 
    /** 
     * 生成Excel文件 
     * @param path         文件路径 
     * @param sheetName    工作表名称 
     * @param dataTitles   数据标题 
     */ 
   public void createExcelFile(String path,String sheetName,String[] dataTitles){  
       WritableWorkbook workbook;  
       try{  
           OutputStream os=new FileOutputStream(path);   
           workbook=Workbook.createWorkbook(os);   
 
           WritableSheet sheet = workbook.createSheet(sheetName, 0); //添加第一个工作表  
           initialSheetSetting(sheet);  
             
           Label label;  
           for (int i=0; i<dataTitles.length; i++){  
               //Label(列号,行号,内容,风格)  
               label = new Label(i, 0, dataTitles[i],getTitleCellFormat());   
               sheet.addCell(label);   
           }  
 
           //插入一行  
           insertRowData(sheet,1,new String[]{"200201001","张三","100","60","100","260"},getDataCellFormat(CellType.STRING_FORMULA));  
             
           //一个一个插入行  
           label = new Label(0, 2,"200201002",getDataCellFormat(CellType.STRING_FORMULA));   
           sheet.addCell(label);  
             
           label = new Label(1, 2,"李四",getDataCellFormat(CellType.STRING_FORMULA));   
           sheet.addCell(label);  
             
           insertOneCellData(sheet,2,2,70.5,getDataCellFormat(CellType.NUMBER));  
           insertOneCellData(sheet,3,2,90.523,getDataCellFormat(CellType.NUMBER));  
           insertOneCellData(sheet,4,2,60.5,getDataCellFormat(CellType.NUMBER));  
 
           insertFormula(sheet,5,2,"C3+D3+E3",getDataCellFormat(CellType.NUMBER_FORMULA));  
             
           //插入日期  
           mergeCellsAndInsertData(sheet, 0, 3, 5, 3, new Date(), getDataCellFormat(CellType.DATE));  
             
           workbook.write();   
           workbook.close();  
       }catch(Exception e){  
           e.printStackTrace();  
       }  
   }  
     
   /** 
    * 初始化表格属性 
    * @param sheet 
    */ 
   public void initialSheetSetting(WritableSheet sheet){  
      try{  
           //sheet.getSettings().setProtected(true); //设置xls的保护,单元格为只读的  
           sheet.getSettings().setDefaultColumnWidth(10); //设置列的默认宽度  
           //sheet.setRowView(2,false);//行高自动扩展   
           //setRowView(int row, int height);--行高   
           //setColumnView(int  col,int width); --列宽  
           sheet.setColumnView(0,20);//设置第一列宽度  
      }catch(Exception e){  
          e.printStackTrace();  
      }  
   }  
     
   /** 
    * 插入公式 
    * @param sheet 
    * @param col 
    * @param row 
    * @param formula 
    * @param format 
    */ 
   public void insertFormula(WritableSheet sheet,Integer col,Integer row,String formula,WritableCellFormat format){  
       try{  
           Formula f = new Formula(col, row, formula, format);  
           sheet.addCell(f);  
       }catch(Exception e){  
           e.printStackTrace();  
       }  
   }  
     
   /** 
    * 插入一行数据 
    * @param sheet       工作表 
    * @param row         行号 
    * @param content     内容 
    * @param format      风格 
    */ 
   public void insertRowData(WritableSheet sheet,Integer row,String[] dataArr,WritableCellFormat format){  
       try{  
           Label label;  
           for(int i=0;i<dataArr.length;i++){  
               label = new Label(i,row,dataArr[i],format);  
               sheet.addCell(label);  
           }  
       }catch(Exception e){  
           e.printStackTrace();  
       }  
   }  
     
   /** 
    * 插入单元格数据 
    * @param sheet 
    * @param col 
    * @param row 
    * @param data 
    */ 
   public void insertOneCellData(WritableSheet sheet,Integer col,Integer row,Object data,WritableCellFormat format){  
       try{  
           if(data instanceof Double){  
               jxl.write.Number  labelNF = new jxl.write.Number(col,row,(Double)data,format);   
               sheet.addCell(labelNF);   
           }else if(data instanceof Boolean){  
               jxl.write.Boolean labelB = new jxl.write.Boolean(col,row,(Boolean)data,format);   
               sheet.addCell(labelB);   
           }else if(data instanceof Date){  
               jxl.write.DateTime labelDT = new jxl.write.DateTime(col,row,(Date)data,format);   
               sheet.addCell(labelDT);   
               setCellComments(labelDT, "这是个创建表的日期说明!");  
           }else{  
               Label label = new Label(col,row,data.toString(),format);  
               sheet.addCell(label);                 
           }  
       }catch(Exception e){  
           e.printStackTrace();  
       }  
 
  }  
     
   /** 
    * 合并单元格,并插入数据 
    * @param sheet 
    * @param col_start 
    * @param row_start 
    * @param col_end 
    * @param row_end 
    * @param data 
    * @param format 
    */ 
   public void mergeCellsAndInsertData(WritableSheet sheet,Integer col_start,Integer row_start,Integer col_end,Integer row_end,Object data, WritableCellFormat format){  
      try{  
          sheet.mergeCells(col_start,row_start,col_end,row_end);// 左上角到右下角  
          insertOneCellData(sheet, col_start, row_start, data, format);  
      }catch(Exception e){  
          e.printStackTrace();  
      }  
 
   }  
     
   /** 
    * 给单元格加注释 
    * @param label 
    * @param comments 
    */ 
   public void setCellComments(Object label,String comments){  
       WritableCellFeatures cellFeatures = new WritableCellFeatures();  
       cellFeatures.setComment(comments);  
       if(label instanceof jxl.write.Number){  
           jxl.write.Number num = (jxl.write.Number)label;  
           num.setCellFeatures(cellFeatures);  
       }else if(label instanceof jxl.write.Boolean){  
           jxl.write.Boolean bool = (jxl.write.Boolean)label;  
           bool.setCellFeatures(cellFeatures);  
       }else if(label instanceof jxl.write.DateTime){  
           jxl.write.DateTime dt = (jxl.write.DateTime)label;  
           dt.setCellFeatures(cellFeatures);  
       }else{  
           Label _label = (Label)label;  
           _label.setCellFeatures(cellFeatures);  
       }  
   }  
     
   /** 
   * 读取excel 
   * @param inputFile 
   * @param inputFileSheetIndex 
   * @throws Exception 
   */ 
   public ArrayList<String> readDataFromExcel(File inputFile, int inputFileSheetIndex){  
      ArrayList<String> list = new ArrayList<String>();  
      Workbook book = null;  
      Cell cell = null;  
      WorkbookSettings setting = new WorkbookSettings();   
      java.util.Locale locale = new java.util.Locale("zh","CN");   
      setting.setLocale(locale);  
      setting.setEncoding("ISO-8859-1");  
      try{  
          book = Workbook.getWorkbook(inputFile, setting);  
      }catch(Exception e){  
          e.printStackTrace();    
      }  
 
      Sheet sheet = book.getSheet(inputFileSheetIndex);  
      for (int rowIndex = 0; rowIndex < sheet.getRows(); rowIndex++) {//行  
       for (int colIndex = 0; colIndex < sheet.getColumns(); colIndex++) {//列  
           cell = sheet.getCell(colIndex, rowIndex);  
           //System.out.println(cell.getContents());  
           list.add(cell.getContents());  
       }  
      }  
      book.close();  
 
      return list;  
   }  
 
   /** 
    * 得到数据表头格式 
    * @return 
    */ 
   public WritableCellFormat getTitleCellFormat(){  
       WritableCellFormat wcf = null;  
       try {  
           //字体样式  
           WritableFont wf = new WritableFont(WritableFont.TIMES,12, WritableFont.NO_BOLD,false);//最后一个为是否italic  
           wf.setColour(Colour.RED);  
           wcf = new WritableCellFormat(wf);  
           //对齐方式  
           wcf.setAlignment(Alignment.CENTRE);  
           wcf.setVerticalAlignment(VerticalAlignment.CENTRE);  
           //边框  
           wcf.setBorder(Border.ALL,BorderLineStyle.THIN);  
             
           //背景色  
           wcf.setBackground(Colour.GREY_25_PERCENT);  
       } catch (WriteException e) {  
        e.printStackTrace();  
       }  
       return wcf;  
   }  
     
   /** 
    * 得到数据格式 
    * @return 
    */ 
   public WritableCellFormat getDataCellFormat(CellType type){  
       WritableCellFormat wcf = null;  
       try {  
           //字体样式  
           if(type == CellType.NUMBER || type == CellType.NUMBER_FORMULA){//数字  
              NumberFormat nf = new NumberFormat("#.00");  
              wcf = new WritableCellFormat(nf);   
           }else if(type == CellType.DATE || type == CellType.DATE_FORMULA){//日期  
               jxl.write.DateFormat df = new jxl.write.DateFormat("yyyy-MM-dd hh:mm:ss");   
               wcf = new jxl.write.WritableCellFormat(df);   
           }else{  
               WritableFont wf = new WritableFont(WritableFont.TIMES,10, WritableFont.NO_BOLD,false);//最后一个为是否italic  
               wcf = new WritableCellFormat(wf);  
           }  
           //对齐方式  
           wcf.setAlignment(Alignment.CENTRE);  
           wcf.setVerticalAlignment(VerticalAlignment.CENTRE);  
           //边框  
           wcf.setBorder(Border.LEFT,BorderLineStyle.THIN);  
           wcf.setBorder(Border.BOTTOM,BorderLineStyle.THIN);  
           wcf.setBorder(Border.RIGHT,BorderLineStyle.THIN);  
           //背景色  
           wcf.setBackground(Colour.WHITE);  
             
           wcf.setWrap(true);//自动换行  
             
       } catch (WriteException e) {  
        e.printStackTrace();  
       }  
       return wcf;  
   }  
     
   /** 
    * 打开文件看看 
    * @param exePath 
    * @param filePath 
    */ 
   public void openExcel(String exePath,String filePath){  
       Runtime r=Runtime.getRuntime();   
       String cmd[]={exePath,filePath};   
       try{   
           r.exec(cmd);   
       }catch(Exception e){  
           e.printStackTrace();  
       }  
   }  
     
   public static void main(String[] args){  
       String[] titles = {"学号","姓名","语文","数学","英语","总分"};   
       JExcelUtils jxl = new JExcelUtils();  
       String filePath = "E:/test.xls";  
       jxl.createExcelFile(filePath," 成绩单",titles);  
       jxl.readDataFromExcel(new File(filePath),0);  
       jxl.openExcel("C:/Program Files/Microsoft Office/OFFICE11/EXCEL.EXE",filePath);  
   }  
} 

 3.下面含有几个十分有用针对excel操作的的工具方法:

 

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jxl.Cell;
import jxl.CellView;
import jxl.Sheet;
import jxl.SheetSettings;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.write.Label;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

/**
 * jxl操作excel的工具类.
 *
 */
public class JxlTool {
	public static int count = 1;
	//存储带有级别信息的内容到位置的映射关系.
	private static Map levelToLocation = new HashMap();
	
	public static void readExcel(String fileName) {
		Workbook wb = null;
		try {
			wb = Workbook.getWorkbook(new File(fileName));
			Sheet[] sheets = wb.getSheets();
			for(int i=0;i<sheets.length;i++){
				Sheet ii = sheets[i];
				System.out.println("第"+i+"个sheet的名字是"+ii.getName());
			}
		} catch (Exception e) {
			System.out.println("出现异常" + e);
			e.printStackTrace();
		} finally {
			wb.close();
		}
	}
	
	private static String allChar = "abcdefghijklmnopqrstuvwxyz";
	/**
	 * 从字符中得到列数.例如K-->10,A-->0,AA-->27
	 * @return
	 */
	public static int getNumFromExcelStr(String code)
 {
  int result = 0;
  code = code.toLowerCase();
  if(code.length()>1){
   char[] c = code.toCharArray();
   int len = c.length;
   for(int i=0;i<len;i++){
    if(i<len-1){
     result+=(allChar.indexOf(c[i])+1)*26; 
    }else{
     result+=allChar.indexOf(c[i])+1;
    }
   }
   result-=1;
  }
  else
   return allChar.indexOf(code);
  return result;
 }	
	/**
	 * 根据行号和列号得到所在的单元格.例如(3,4)-->"E4"
	 * @param vNum 纵坐标
	 * @param hNum 横坐标
	 * @return
	 */
	public static String getCellInfo(int hNum,int vNum){
		char[] cs = allChar.toCharArray();
		String hStr = "";
		if(vNum>25){
			hStr = String.valueOf(cs[vNum/26-1])+String.valueOf(cs[vNum%26-1]);
		}else{
			hStr = String.valueOf(cs[vNum]);
		}
		return (hStr+Integer.toString((hNum+1))).toUpperCase();
	}

	/**
	 * 得到一个字符串里面的字符.A12-->A
	 * @param oldStr
	 * @return
	 */
	public static String getCodeFromStr(String oldStr){
		return oldStr.replaceAll("\\d", "");
	}
	
	/**
	 * 得到一个字符串里面的字符.A12-->12
	 * @param oldStr
	 * @return
	 */
	public static int getNumFromStr(String oldStr){
		return Integer.parseInt(oldStr.replaceAll("[a-zA-Z]", ""))-1;
	}
	
	/**
	 * 读取指定excel中的指定sheet的某一块的数据....用于模板里面读取单元格.
	 * @param fileName
	 * @param sheetIndex
	 * @param startRow
	 * @param endRow
	 * @param startColumn
	 * @param endColumn
	 */
	public static List readExcel(String fileName, int sheetIndex, int startRow,
			int endRow, int startColumn, int endColumn) {
		Workbook wb = null;
		List allData = new ArrayList();
		Cell cell = null;
		try {
			wb = Workbook.getWorkbook(new File(fileName));
			Sheet sheet = wb.getSheet(sheetIndex);
			int rowCount = sheet.getRows();
			int columnCount = sheet.getColumns();
			for (int r = startRow; r < rowCount && r <= endRow; r++) {// 行
				for (int c = startColumn; c < columnCount && c <= endColumn; c++) {// 列
					cell = sheet.getCell(c, r);
					// System.out.println(cell.getContents());
					allData.add(cell.getContents());
				}
			}
		} catch (Exception e) {
			System.out.println("出现异常" + e);
			e.printStackTrace();
		} finally {
			wb.close();
		}
		return allData;
	}
	
	/**
	 * 读取指定excel中的指定sheet的某一块的数据....用于模板里面读取单元格.
	 * @param fileName
	 * @param sheetIndex
	 * @param startCell
	 * @param endCell
	 * @return
	 */
	public static List readExcel(String fileName, int sheetIndex,String startCell, String endCell) {
		int startRow = getNumFromStr(startCell);
		int endRow = getNumFromStr(endCell);
		int startColumn=getNumFromExcelStr(getCodeFromStr(startCell));
		int endColumn = getNumFromExcelStr(getCodeFromStr(endCell));
		return readExcel(fileName, sheetIndex, startRow, endRow, startColumn,
				endColumn);
	}
		
	/**
	 * 设置excel中的sheet页全部隐藏
	 * @param fileName
	 */
	public static void setAllHiddenSheet(String fileName) {
		Workbook wb = null;
		try {
			wb = Workbook.getWorkbook(new File(fileName));
			// 打开一个文件副本,并指定数据写回原文件.
			WritableWorkbook book = Workbook.createWorkbook(new File(fileName),
					wb);
			Sheet[] sheets = book.getSheets();
			for(int i=3;i<sheets.length;i++){
				Sheet ii = sheets[i];
				ii.getSettings().setHidden(true);
			}
			book.write();
			book.close();
		} catch (Exception e) {
			System.out.println("出现异常" + e);
			e.printStackTrace();
		} finally {
			wb.close();
			System.out.print(111);
		}
	} 

       /**
          * 从行号和列号,得到所在的位置字符串,例如:row=7,col=7--->i8
          */
        public  static String getcodefromRC(int row,int col){
		char[] cc = allChar.toCharArray();
		return String.valueOf(cc[col])+(++row);
	}
    
	/**
	 * 添加一个新的sheet到指定excel文件
	 * @param fileName
	 * @param sheetName sheet的name
	 */
	public static void addNewSheet(String fileName,String sheetName) {
		Workbook wb = null;
		try {
			wb = Workbook.getWorkbook(new File(fileName));
			// 打开一个文件副本,并指定数据写回原文件.
			WritableWorkbook book = Workbook.createWorkbook(new File(fileName),
					wb);
			// 创建一个新的sheet到第2页的位置			
			String[] sheetNames = wb.getSheetNames();
			for(int i=0;i<sheetNames.length;i++){
				if(sheetNames[i].equals(sheetName)){
					System.out.println("已经存在了,不用添加了." );
					return ;
				}
			}
			WritableSheet sheet = book.createSheet(sheetName, 1);
			sheet.addCell(new Label(0, 0, "新加的测试数据"));
			book.write();
			book.close();
		} catch (Exception e) {
			System.out.println("出现异常" + e);
			e.printStackTrace();
		} finally {
			wb.close();
		}
	} 

        /**
          * 得到单元格的double内容,不可以直接使用cell.getContents(),因为这个方法是直接打印单元格内容
,单元格内容可能隐藏了后面的小数点!!        
          */
         public static double getNumber(Cell cell){
             NumberCell numberCell = (NumberCell)cell; 
            double namberValue = numberCell.getValue(); 
             return   namberValue ;         
         }

         /**
	 * 如果是公式返回公式的内容,否则返回单元格字符串表面内容
	 * @param c
	 * @return
	 */
         public static String getForJmulaStr(Cell c) {
		String ans = "";
		try {
			System.out.println(c.getType());
			if (c.getType() == CellType.NUMBER_FORMULA
					|| c.getType() == CellType.STRING_FORMULA
					|| c.getType() == CellType.BOOLEAN_FORMULA
					|| c.getType() == CellType.DATE_FORMULA
					|| c.getType() == CellType.FORMULA_ERROR) {
				FormulaCell nfc = (FormulaCell) c;
				ans = nfc.getFormula();
				
			} else {
				ans = c.getContents();
			}
		} catch (FormulaException e) {
			return "出现异常" + e.getMessage();
		} 
		return ans;
	}

      //得到指定位置单元格的值(普通单元格,数字单元格,日期单元格)
       private String getValue(Sheet sheet,int row,int col){
    	Cell cell=sheet.getCell(col, row);   
    	CellType cellType=cell.getType();
		NumberCell numberCell = null;
		String cellValue = "";
        //得到单元格的值
        if (cellType == CellType.NUMBER) {
	      numberCell = (NumberCell) cell;
	      cellValue = String.valueOf(numberCell.getValue());
       } else if (cellType == CellType.DATE) {
				cellValue = df.format(((DateCell) cell).getDate());
	 } else if (cellType == CellType.NUMBER_FORMULA) { 
		 // 形如:=123.232+3423.12
		 // 或者 =B2+123.12
		 NumberFormulaCell numberFormulaCell = (NumberFormulaCell) cell;
		 cellValue = String.valueOf(numberFormulaCell.getValue());
	 } else {
		 cellValue = cell.getContents();
	 }       
       cellValue=cellValue.replace(" ", "");  
        return cellValue;
    }
}
分享到:
评论
14 楼 liushuli81 2012-03-23  
楼主,你知道用jxl怎么实现单元格的对角线么??知道麻烦回答一下。。
13 楼 renjie120 2011-08-19  
gaoyibin 写道
楼主,你知道用jxl怎么实现单元格的对角线么??知道麻烦回答一下。。

不知道...没有做个这个需求..
12 楼 gaoyibin 2011-08-19  
楼主,你知道用jxl怎么实现单元格的对角线么??知道麻烦回答一下。。
11 楼 socker 2010-07-16  
<p>
</p>
<pre name="code" class="java">
//查询信息表对应的有效合同
@SuppressWarnings("unchecked")
public TKamContract getTKamContractByKamID(Long kamid){
BeanQueryCondition bqc = BeanQueryCondition.forClass(TKamContract.class);
bqc.addExpressions(Restrictions.and(Restrictions.equal("kamid", kamid),
Restrictions.equal("delflag", 0L)
// Restrictions.equal("contractstatus", 0L)//hchang 现在无需判断合同是否有效了
// Restrictions.notEqual("policytype", "6")//非超额
));
bqc.addInitFields("TKam");
List&lt;TKamContract&gt; result =  getEntityManager().query(bqc);
// String hql = "from TKamContract t where t.TKam.kamid="+kamid+" and t.delflag=0 and t.contractstatus=0";
// TKamContract result = (TKamContract)getEntityManager().queryForObjectByHql(hql);
if(result!=null &amp;&amp; result.size()&gt;0){
return result.get(0);
}
else{
return null;
}
}</pre>
 
10 楼 renjie120 2010-07-15  
while(m.find()){  
             count++;  
             str = str.replaceFirst(regexStr, "");  
         }  


这个replace是没有必要的,find会更新下一次查找的开始位置


---------------------------------------------
是的,我的有问题,谢谢提醒
9 楼 weiqiang.yang 2010-07-15  
while(m.find()){  
             count++;  
             str = str.replaceFirst(regexStr, "");  
         }  


这个replace是没有必要的,find会更新下一次查找的开始位置

/**
     * Attempts to find the next subsequence of the input sequence that matches
     * the pattern.
     *
     * <p> This method starts at the beginning of this matcher's region, or, if
     * a previous invocation of the method was successful and the matcher has 
     * not since been reset, at the first character not matched by the previous
     * match.
     *
     * <p> If the match succeeds then more information can be obtained via the
     * <tt>start</tt>, <tt>end</tt>, and <tt>group</tt> methods.  </p>
     *
     * @return  <tt>true</tt> if, and only if, a subsequence of the input
     *          sequence matches this matcher's pattern
     */
    public boolean find() {
        int nextSearchIndex = last;
        if (nextSearchIndex == first)
            nextSearchIndex++;

        // If next search starts before region, start it at region
        if (nextSearchIndex < from)
            nextSearchIndex = from;

        // If next search starts beyond region then it fails
        if (nextSearchIndex > to) {
            for (int i = 0; i < groups.length; i++)
                groups[i] = -1;
            return false;
        }
        return search(nextSearchIndex);
    }
8 楼 chw8219 2010-07-15  
作为资料收藏,3q.
7 楼 renjie120 2010-07-14  
richarwu 写道
我看标题以为是jxl中用到了正则,一直以这个想法阅读,最后看到回复了。

呵呵,说实话我在项目中确实使用jxl的同时使用了正则表达式,需求是这样的:把excel中的公式转换为业务sql语句。
具体的情况具体分析,还是有机会遇到了。
6 楼 dingherry 2010-07-14  
难道我是第6个回复的?
5 楼 richarwu 2010-07-14  
我看标题以为是jxl中用到了正则,一直以这个想法阅读,最后看到回复了。
4 楼 bluethink 2010-07-14  
正好可以学习Java操作EXCEL 和 正则,支持楼主
3 楼 renjie120 2010-07-14  
taoyu3781212 写道
lz看了你的文章,感觉正则表达式跟读取excel没什么关系吧,怎么放到一起呢,感觉有点乱

我放在一起并不是表示这两个有关系,而是我的一个系统的知识的累积!呵呵,你多虑了.
2 楼 taoyu3781212 2010-07-14  
lz看了你的文章,感觉正则表达式跟读取excel没什么关系吧,怎么放到一起呢,感觉有点乱
1 楼 zhao103804 2010-07-14  
真是学习了,我们的项目中最多就是一个生成excel文件
还没有做到LZ系统的地步

相关推荐

Global site tag (gtag.js) - Google Analytics