利用poi实现解析Excel

直接就能用,进行excel的解析

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * class name:解析xml
 * class description: please write your description <BR>
 * Remark: <BR>
 * @version 1.00 2015年7月29日
 * @author JFTT)liucaibao
 */
public class XlsParserUtil {
/*	public static String csvToTxt(String path,String unicode,int startRowNum,int endRowNum,Map<Integer,Integer> useColumn ) throws IOException{
		FileInputStream fr = new FileInputStream(path);
		CSVReader csvReader = new CSVReader(new InputStreamReader(fr, unicode));
		File outPutFile = new File(path+".txt");
		if(outPutFile.exists()){
			FileUtil.deleteFile(outPutFile);
		}
		FileOutputStream fos = new FileOutputStream(outPutFile, true);
		BufferedOutputStream Buff=new BufferedOutputStream(fos);
		// first row is title, so past
		String[] csvRow = null;// row
		int count = 0;
		if(endRowNum == 0){
			endRowNum = Integer.MAX_VALUE;
		}
		while ((csvRow = csvReader.readNext()) != null) {
			if(count>=startRowNum-1 && count <= endRowNum-1){
				for (int i = 0; i < csvRow.length; i++) {
					if(useColumn.get(i)==null){
						continue;
					}
					Buff.write(csvRow[i].getBytes(unicode));
					Buff.write("\t".getBytes());
				}
				Buff.write("\n".getBytes());
			}
			count++;
			if (count >= endRowNum) {
				break;
			}
		}
		Buff.flush();
		Buff.close();
		FileUtil.deleteFile(path);
		return path+".txt";
	}*/
	public static String xlsToTxt(String path,String unicode,int startRowNum,int endRowNum,Map<Integer,Integer> useColumn) throws IOException{
		FileInputStream fr = new FileInputStream(path);
		File outPutFile = new File(path+".txt");
		if(outPutFile.exists()){
			FileUtil.deleteFile(outPutFile);
		}
		FileOutputStream fos = new FileOutputStream(outPutFile, true);
		BufferedOutputStream Buff=new BufferedOutputStream(fos);
		int count = 0;
		if(endRowNum == 0){
			endRowNum = Integer.MAX_VALUE;
		}
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook(fr);
		// 循环工作表Sheet
		for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets() && numSheet==0; numSheet++) {
			HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
			if (hssfSheet == null) {
				continue;
			}

			// 循环行Row
			for (int rowNum = 0; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
				HSSFRow hssfRow = hssfSheet.getRow(rowNum);
				if (hssfRow == null) {
					continue;
				}
				if(count>=startRowNum-1 && count <= endRowNum-1){
					// 循环列Cell
					for (int cellNum = 0; cellNum <= hssfRow.getLastCellNum(); cellNum++) {
						if(useColumn.get(cellNum)==null){
							continue;
						}
						HSSFCell hssfCell = hssfRow.getCell(cellNum);
						if (hssfCell == null) {
							Buff.write("".getBytes(unicode));
						}else{
							Buff.write(getValue(hssfCell).getBytes(unicode));
						}
						Buff.write("\t".getBytes());
					}
					Buff.write("\n".getBytes());
				}
				count++;
				if (count >= endRowNum) {
					break;
				}
			}
		}
		Buff.flush();
		Buff.close();
		FileUtil.deleteFile(path);
		return path+".txt";
	}
	public static String xlsxToTxt(String path,String unicode,int startRowNum,int endRowNum,Map<Integer,Integer> useColumn) throws IOException{
		FileInputStream fr = new FileInputStream(path);
		File outPutFile = new File(path+".txt");
		FileUtil.deleteFile(outPutFile);
		FileOutputStream fos = new FileOutputStream(outPutFile, true);
		BufferedOutputStream Buff=new BufferedOutputStream(fos);
		if(endRowNum == 0){
			endRowNum = Integer.MAX_VALUE;
		}
		// first row is title, so past
		XSSFWorkbook wb = null;
        try {
            wb = new XSSFWorkbook(fr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (wb != null && wb.getNumberOfSheets() > 0) {
            try {
                // get first sheet object
                XSSFSheet sheet = wb.getSheetAt(0);
                // get current Workbook rows
                int rowNum = sheet.getLastRowNum();
                for (int i = 0;i < rowNum;i++) {
                    // get current row cells
                	if(i>=startRowNum-1 && i <= endRowNum-1){
	                    XSSFRow row = sheet.getRow(i);
	                    int cellNum = row.getLastCellNum();
	                    if (cellNum > 0) {
	                        for (int j = 0;j < cellNum;j++) {
	                        	if(useColumn.get(j)==null){
	    							continue;
	    						}
	                            XSSFCell cell = row.getCell(j);
	                            Buff.write(getValue(cell).getBytes(unicode));
	        					Buff.write("\t".getBytes());
	                        }
	                    } else {
	                        throw new RuntimeException("No cells found in excel .");
	                    }
	                    Buff.write("\n".getBytes());
                	}
                    if (i >= endRowNum) {
    					break;
    				}
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            throw new RuntimeException("Please select a valided excel file !");
        }
		Buff.flush();
		Buff.close();
		FileUtil.deleteFile(path);
		return path+".txt";
	}
	// csv数据解析方法
	/*public static JSONArray importCsvParser(String path, String unicode, int csvHeadRowNum,int startNum,int endNum) throws IOException {
		FileInputStream fr = new FileInputStream(path);
		CSVReader csvReader = new CSVReader(new InputStreamReader(fr, unicode));
		// 看有没有标题列
		String[] csvRow = null;// row
		JSONArray result = new JSONArray();
		//先把标题行留着
		result.add(new JSONArray());
		//这个是计数,统计数据行数
		int count = 0;
		if(endNum == 0){
			endNum = Integer.MAX_VALUE;
		}
		while ((csvRow = csvReader.readNext()) != null) {
			JSONArray rowJsonArray = new JSONArray();
			for (int i = 0; i < csvRow.length; i++) {
				if(csvHeadRowNum == count+1 && csvRow[i].equals("")){
					rowJsonArray.add("COL_"+i);
				}else{
					rowJsonArray.add(csvRow[i]);
				}
			}
			//循环第一行时,拼接一个临时标题
			if(csvHeadRowNum == 0 && count == 0){
				JSONArray headRowJsonArray = new JSONArray();
				for(int i = 0; i < csvRow.length; i++){
					headRowJsonArray.add("COL_"+i);
				}
				result.add(0, headRowJsonArray);
				if(count>=startNum-1 && count <= endNum-1){
					result.add(rowJsonArray);
				}
			}else if(csvHeadRowNum == count+1){
				result.add(0, rowJsonArray);
			}else{
				if(count>=startNum-1 && count <= endNum-1){
					result.add(rowJsonArray);
				}
			}
			count++;
			if (count >= endNum) {
				break;
			}
		}
		return result;
	}*/

	/**
	 * @throws IOException
	 *
	 */
	public static JSONArray importXlsParser(String path, String unicode, int csvHeadRowNum,int startNum,int endNum) throws IOException {
		JSONArray result = new JSONArray();
		//先把标题行留着
		result.add(new JSONArray());
		int count = 0;
		if(endNum == 0){
			endNum = Integer.MAX_VALUE;
		}
		File file = new File(path);
		InputStream is = new FileInputStream(file);
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
		// 循环工作表Sheet
		for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets() && numSheet==0; numSheet++) {
			HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
			if (hssfSheet == null) {
				continue;
			}

			// 循环行Row
			for (int rowNum = 0; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
				JSONArray rowJsonArray = new JSONArray();
				HSSFRow hssfRow = hssfSheet.getRow(rowNum);
				if (hssfRow == null) {
					continue;
				}

				// 循环列Cell
				for (int cellNum = 0; cellNum <= hssfRow.getLastCellNum(); cellNum++) {
					HSSFCell hssfCell = hssfRow.getCell(cellNum);
					if(csvHeadRowNum == count+1 && getValue(hssfCell).equals("")){
						rowJsonArray.add("COL_"+cellNum);
					}else{
						rowJsonArray.add(getValue(hssfCell));
					}
				}
				//循环第一行时,拼接一个临时标题
				if(csvHeadRowNum == 0 && count == 0){
					JSONArray headRowJsonArray = new JSONArray();
					for(int i = 0; i < hssfRow.getLastCellNum(); i++){
						headRowJsonArray.add("COL_"+i);
					}
					result.add(0, headRowJsonArray);
					if(count>=startNum-1 && count <= endNum-1){
						result.add(rowJsonArray);
					}
				}else if(csvHeadRowNum == count+1){
					result.add(0, rowJsonArray);
				}else{
					if(count>=startNum-1 && count <= endNum-1){
						result.add(rowJsonArray);
					}
				}
				count++;
				if (count >= endNum) {
					break;
				}
			}
		}
		return result;
	}

	public static int  getXLSNum(String path,String fileType){
		File file = new File(path);

		if("xlsx".equals(fileType)){
			XSSFWorkbook wb = null;
			try {
				wb = new XSSFWorkbook(new FileInputStream(file));
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (wb != null && wb.getNumberOfSheets() > 0) {
				try {
					// get first sheet object
					XSSFSheet sheet = wb.getSheetAt(0);
					// get current Workbook rows
					int rowNum = sheet.getLastRowNum();
					return rowNum;
				}
				catch(Exception e){
					System.out.println(e);
				}

			}
		}else {

			try {
				HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(file));
				HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);

				int rowNum = hssfSheet.getLastRowNum();
				return rowNum;
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return 0;
	}

	public static JSONArray importXlsxParser(String path, String unicode, int csvHeadRowNum,int startNum,int endNum) {
		JSONArray result = new JSONArray();
		//先把标题行留着
		result.add(new JSONArray());
		if(endNum == 0){
			endNum = Integer.MAX_VALUE;
		}
		File file = new File(path);
		XSSFWorkbook wb = null;
        try {
            wb = new XSSFWorkbook(new FileInputStream(file));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (wb != null && wb.getNumberOfSheets() > 0) {
            try {
                // get first sheet object
                XSSFSheet sheet = wb.getSheetAt(0);
                // get current Workbook rows
                int rowNum = sheet.getLastRowNum();
                for (int i = 0;i < rowNum;i++) {
                	JSONArray rowJsonArray = new JSONArray();
                    // get current row cells
                    XSSFRow row = sheet.getRow(i);
                    int cellNum = row.getLastCellNum();
                    if (cellNum > 0) {
                        for (int j = 0;j < cellNum;j++) {
                            XSSFCell cell = row.getCell(j);
                            if(csvHeadRowNum == i+1 && getValue(cell).equals("")){
        						//rowJsonArray.add("COL_"+j);
        					}else{
        						rowJsonArray.add(getValue(cell));
        					}

                        }
                      //循环第一行时,拼接一个临时标题
        				if(csvHeadRowNum == 0 && i == 0){
        					JSONArray headRowJsonArray = new JSONArray();
        					for(int j = 0; j < cellNum; j++){
        						//headRowJsonArray.add("COL_"+j);
        					}
        					result.add(0, headRowJsonArray);
        					if(i>=startNum-1 && i <= endNum-1){
        						result.add(rowJsonArray);
        					}
        				}else if(csvHeadRowNum == i+1){
        					result.add(0, rowJsonArray);
        				}else{
        					if(i>=startNum-1 && i <= endNum-1){
        						result.add(rowJsonArray);
        					}
        				}
                    } else {
                        throw new RuntimeException("No cells found in excel .");
                    }

                    if (i+1 >= endNum) {
    					break;
    				}
                }
            } catch (Exception e) {
            	return result;
            }
        } else {
            return result;
        }
        return result;

	}

	private static String getValue(Cell cell) {
		if (null != cell) {
            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC: // 数字
            	if(HSSFDateUtil.isCellDateFormatted(cell)){
    				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    				return sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString();
    			}else{
    				// 是否为数值型
					double d = cell.getNumericCellValue();
					if (d - (int) d < Double.MIN_VALUE) {
						// 是否为int型
						return Integer.toString((int) d);
					} else {
						// 是否为double型
						DecimalFormat df = new DecimalFormat("########.#######");
						return df.format(cell.getNumericCellValue());
					}
				}
            case Cell.CELL_TYPE_STRING: // 字符串
            	return cell.getStringCellValue();
            case Cell.CELL_TYPE_BOOLEAN: // Boolean
            	return Boolean.toString(cell.getBooleanCellValue());
            case Cell.CELL_TYPE_FORMULA: // 公式
            	return cell.getCellFormula();
            case Cell.CELL_TYPE_BLANK: // 空值
            	return "";
            case Cell.CELL_TYPE_ERROR: // 故障
            	return "";
            default:
            	return "";
            }
        } else {
        	return "";
        }
	}
	}
时间: 2024-08-04 19:16:45

利用poi实现解析Excel的相关文章

Java利用POI导入导出Excel中的数据

     首先谈一下今天发生的一件开心的事,本着一颗android的心我被分配到了PB组,身在曹营心在汉啊!好吧,今天要记录和分享的是Java利用POI导入导出Excel中的数据.下面POI包的下载地址http://poi.apache.org/download.html,有兴趣的朋友也可以去看看其中的API.      下面分享一下在对POI进行基本操作时觉得需要注意的两点:       1.POI中针对xlsx/xls是需要create different Workbook instance

java利用poi包 为excel生成超链接

转载自:http://www.blogjava.net/leekiang/archive/2008/10/21/235794.html 1,一个需求, 要求报表生成的Excel表格支持超链接.例如点击Excel内的公司名, 自动打开浏览器并连到该公司的网站上去.在Excel里面选中所需的单元格, 右键弹出属性, 选超链接就能输入相应的地址了,既然Excel支持超链接.那就没有什么借口说不能实现了.:). 翻了翻POI的文档, 很容易就找到了解决方案.在POI中让单元格实现超链接功能, 可以用Hy

java 使用 poi 解析excel

背景: web应用经常需要上传文件,有时候需要解析出excel中的数据,如果excel的格式没有问题,那就可以直接解析数据入库. 工具选择: 目前jxl和poi可以解析excel,jxl很早就停止维护了,只支持excel-2003也就是xls格式的文件: poi可支持xls和xlsx格式的文件,经过考察,poi的功能强大很多,所以选择这个工具解析excel.文件上传在之前的一个专题有所提及. 需要如下jar包,jar包见附件,也可在官网下载. 注意: 1. 不支持单元格合并的情况,默认表格格式规

Poi解析Excel

Poi解析Excel Poi包里有4个主要的类,包括: Workbook------工作表,通过WorkbookFactory的create(FileInputStream fis)方法获取, Sheet------------表格,Workbook实例的getSheetAt(int num)方法获取, Row--------------行,Sheet实例的getRow(int num)方法获取, Cell--------------单元格,Row实例的getCell(int num)方法获取,

使用POI解析Excel时,出现org.xml.sax.SAXParseException: duplicate attribute &#39;o:relid&#39;的解决办法

1.使用org.apache.poi解析excle,.xlsx类型文件InputStream is = new FileInputStream(strFileName);XSSFWorkbook wb = new XSSFWorkbook(is);出现异常如下: org.apache.poi.POIXMLException: java.lang.reflect.InvocationTargetExceptionat org.apache.poi.xssf.usermodel.XSSFFactor

Apache POI解析Excel文件

1.导入POI的jar包到BOS项目中 2. 使用POI解析Excel文件

POI解析excel的漏洞(CVE-2014-3574)

一.概述 最早的时候,java开发人员在操作excel的时候,用的最多的框架应该是poi.jxl.随着office的不断发展,office2007开始支持openXML的协议,后续陆续出现了新的框架支持操作office,如docx4j等.openXML使得数据的结构.组成更加透明,可以通过一定的操作看到内部完整的结构,如果仔细研究内部的属性,还可以进行更深层次的操作.当然,有利有弊,这也在一定程度上带来了麻烦,因为文件可以随意的更改内部的组成,在一定程度上给相关系统造成麻烦. 二.excel20

Java利用POI生成Excel强制换行

前一段时间在做一个学校排课系统时,有一个地方需要利用把课程表生成excel汇出给客户,由于之前用excel都只是简单的应用,在单元格里都是用自动换行,而这次可能需要用到手动强制换行. 于是我在网上找了一下,网上找到的文章都是说在excel里的文字里加上/n,/n/r,/r/n之类,反正各种各样的都有,更奇怪的是还有人说在单元格里加上<br> 后来我试过用/r后的效里是生成的文件里,你用打开时,并不会换行,如果你用鼠标在单元格里点一下之后就会自动换行. 后来我琢磨了一下,可以通过如下方式进行, 

框架 day50 BOS项目 4 批量导入(ocupload插件,pinyin4J)/POI解析Excel/Combobox下拉框/分区组合条件分页查询(ajax)/分区数据导出(Excel)

知识点: 批量导入(ocupload插件,pinyin4J /POI解析Excel(apache POI) /区域分页查询 /Combobox下拉框 /分区组合条件分页查询(ajax) /分区数据导出(Excel下载) BOS项目笔记第4天 1.    区域批量导入功能 *Ajax不支持文件上传. *上传并且不刷新上传页面原理: Target到一个0,0,0的隐藏iframe里,造成一个没有刷新的假象 <form target="myIframe" action="ab