博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用POI分割纯文本Excel文件 Version0.2 支持XLSX\XLS
阅读量:6458 次
发布时间:2019-06-23

本文共 5319 字,大约阅读时间需要 17 分钟。

  hot3.png

使用POI分割纯文本Excel文件  并保留文件的首行格式

POI 3.12 支持XLS和XLSX 

PS:怎么才能复制一个workbook对象呢...求解

package com.sgmder.java;import java.io.FileInputStream;import java.io.FileOutputStream;import java.text.DecimalFormat;import java.util.LinkedList;import java.util.List;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.Row;import org.apache.poi.ss.usermodel.Sheet;import org.apache.poi.ss.usermodel.Workbook;import org.apache.poi.xssf.usermodel.XSSFWorkbook;/** * 分割Excel文件 保留首行格式 *  * @author sgmder * @version 0.2 * */public class SplitExcelOne2MoreSaveFormat {	private String fileName;	private Workbook workBook;	private int i = 1;	private String preName = "split";	private String path = "C:\\test";	private String extend;	public static void main(String[] arg) throws Exception {		SplitExcelOne2MoreSaveFormat rw = new SplitExcelOne2MoreSaveFormat("C:\\test.xls");		//path + preName+ i++ + entend		rw.setPath("C:\\test\\");		rw.setPreName("splitFile_");		// 文件长度固定		rw.splitExcelByLength(1);		// 文件个数固定		//rw.splitExcelByNum(1);	}		/**	 * 写文件	 * @throws Exception	 */	private void writeFile() throws Exception{			FileOutputStream fOut = new FileOutputStream(path+					 preName +i++ +extend);			workBook.write(fOut);			fOut.flush();			fOut.close();	}	public SplitExcelOne2MoreSaveFormat(String fileName) {		this.fileName = fileName;	}	/**	 * 获取工作簿	 * 	 * @return	 * @throws Exception	 */	private Workbook getWorkbook() {		if (workBook == null) {			try {				if (fileName.substring(fileName.lastIndexOf('.') + 1)						.equalsIgnoreCase("xlsx")) {					workBook = new XSSFWorkbook(new FileInputStream(fileName));					extend = ".xlsx";				} else if (fileName.substring(fileName.lastIndexOf('.') + 1)						.equalsIgnoreCase("xls")) {					workBook = new HSSFWorkbook(new FileInputStream(fileName));					extend = ".xls";				} else {					throw new IllegalArgumentException("非EXCEL文件类型!");				}			} catch (Exception e) {				e.printStackTrace();			}		}		return workBook;	}	/**	 * 文件长度固定 分割EXCEL文件	 * 	 * @param length	 * @return	 */	public List
splitExcelByLength(int length) throws Exception{ List
bookList = new LinkedList
(); int rows = getWorkbook().getSheetAt(0).getLastRowNum(); int count = rows / length; return NewWorkbook(length, bookList, rows, count); } /** * 文件个数固定 分割EXCEL文件 * * @param count * @return */ public List
splitExcelByNum(int count) throws Exception{ List
bookList = new LinkedList
(); int rows = getWorkbook().getSheetAt(0).getLastRowNum(); count = rows % count != 0 ? count - 1 : count; int length = rows / count; return NewWorkbook(length, bookList, rows, count); } /** * 获取WorkbookList * * @param length * @param bookList * @param rows * @param count * @return */ private List
NewWorkbook(int length, List
bookList, int rows, int count) throws Exception{ List
list = new LinkedList
(); for (int x = 1; x <= count; x++) { list.add( getExcelContent((x - 1) * length + 1, x * length)); } if (rows % length != 0) { list.add( getExcelContent(count * length + 1, rows)); } for(String str:list) getNewWorkbook(str); return bookList; } /** * 获取Excel内容 * * @param startNum * @return */ private String getExcelContent(int... startNum) { int start = startNum.length > 0 ? startNum[0] : 0; int end = startNum.length > 1 ? startNum[1] > getWorkbook().getSheetAt( 0).getLastRowNum() ? getWorkbook().getSheetAt(0) .getLastRowNum() : startNum[1] : getWorkbook().getSheetAt(0) .getLastRowNum(); StringBuffer sb = new StringBuffer(); while (start <= end) { sb.append(getRowValue(start++)); } return sb.toString(); } /** * 获取一行数据 * * @param rowNum * @return */ private String getRowValue(int rowNum) { Sheet sheet = getWorkbook().getSheetAt(0); Row row = sheet.getRow(rowNum); int cellNum = row.getLastCellNum(); StringBuffer result = new StringBuffer(); for (int j = 0; j < cellNum; j++) { if (row.getCell((short) j) != null) { if (row.getCell((short) j).getCellType() == 1) { result.append(row.getCell((short) j).getStringCellValue()); } else if (row.getCell((short) j).getCellType() == 0) { DecimalFormat df = new DecimalFormat("0"); String strCell = df.format(row.getCell((short) j) .getNumericCellValue()); result.append(strCell); } } result.append("\t"); } result.setLength(result.length() - 1); result.append("\n"); return result.toString(); } /** * 获取新的Workbook * @param workbook * * @param ExcelContent * @return */ private void getNewWorkbook(String ExcelContent) throws Exception{ clear(); Workbook workbook = getWorkbook(); Sheet sheet = workbook.getSheetAt(0); String[] rows = ExcelContent.split("\n"); for (int i = 0; i < rows.length; i++) { Row row = sheet.createRow((short) (i+1)); String[] cells = rows[i].split("\t"); for (int j = 0; j < cells.length; j++) { Cell cell = row.createCell((short) j); cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellValue(cells[j]); } } writeFile(); } /** * 清除除了title之外的行 */ private void clear(){ Sheet sheet = getWorkbook().getSheetAt(0); while( sheet.getLastRowNum() > 0) sheet.removeRow(sheet.getRow(sheet.getLastRowNum())); } public void setPath(String path){ this.path = path; } public void setPreName(String preName){ this.preName = preName; }}

 

转载于:https://my.oschina.net/sgmder/blog/680381

你可能感兴趣的文章
DB2 错误码解析
查看>>
读书笔记四
查看>>
JAVA中的finalize()方法
查看>>
慕课网学习手记--炫丽的倒计时效果Canvas绘图与动画基础
查看>>
==与equals()的区别
查看>>
TCP三次握手四次挥手相关问题探讨
查看>>
基本分类方法——KNN(K近邻)算法
查看>>
在XenCenter6.2中构建CentOS7虚拟机的启动错误
查看>>
.NET Framework3.0/3.5/4.0/4.5新增功能摘要
查看>>
php中表单提交复选框与下拉列表项
查看>>
熟悉常用的Linux操作
查看>>
WordPress 前端投稿/编辑发表文章插件 DJD Site Post(支持游客和已注册用户)汉化版 免费下载...
查看>>
C# 自定义事件整理项目 - EventDemo
查看>>
几何面积体积_2
查看>>
面象过程与面象对象
查看>>
用CSS实现图片水印效果代码
查看>>
谷歌设置支持webgl
查看>>
P3402 【模板】可持久化并查集
查看>>
js的AJAX请求有关知识总结
查看>>
Eclipse添加新server时无法选择Tomcat7的问题
查看>>