------------------------------------------------------初始化xls操纵类--------

import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
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.Region;
import org.apache.poi.poifs.filesystem.POIFSFileSystem; /**
* 功能描述: Excel操纵类
* @author: andy.li
* @date: 2011-4-22
*/
public class StyleExcelTemplate {
private static Log logger = LogFactory.getLog(StyleExcelTemplate.class);
private static final String DATAS = "datas"; private HSSFWorkbook workbook;
private HSSFSheet sheet;
private HSSFRow currentRow;
private Map styles = new HashMap(); //数据行的默认样式配置
private Map confStyles = new HashMap(); //通过设置"#STYLE_XXX"来标识的样式配置
private int initrow; //数据输出起始行
private int initcol; //数据输出起始列
private int num; //index number
private int currentcol; //当前列
private int currentRowIndex; //当前行index
private int rowheight = 22; //行高
private int lastLowNum = 0;
private String cellStyle = null; private StyleExcelTemplate() {
} /**
* 使用默认模板创建ExcelTemplate对象
* @return 根据模板已初始化完成的ExcelTemplate对象
*/
public StyleExcelTemplate newInstance(){
return newInstance("templates/default.xls");
} /**
* 指定模板创建ExcelTemplate对象
* @param templates 模板名称
* @return 根据模板已初始化完成的ExcelTemplate对象
*/
public static StyleExcelTemplate newInstance(String templates){
try {
StyleExcelTemplate excel = new StyleExcelTemplate();
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(new File(templates)));
excel.workbook = new HSSFWorkbook(fs);
excel.sheet = excel.workbook.getSheetAt(0);
//查找配置
excel.initConfig();
//查找其它样式配置
excel.readCellStyles();
//删除配置行
excel.sheet.removeRow( excel.sheet.getRow(excel.initrow) );
return excel;
} catch (Exception e) {
e.printStackTrace();
logger.trace("创建Excel对象出现异常",e);
throw new RuntimeException("创建Excel对象出现异常");
}
} /**
* 设置特定的单元格样式,此样式可以通过在模板文件中定义"#STYLE_XX"来得到,如:
* #STYLE_1,传入的参数就是"STYLE_1"
* @param style
*/
public void setCellStyle(String style){
cellStyle = style;
} /**
* 取消特定的单元格格式,恢复默认的配置值,即DATAS所在行的值
*/
public void setCellDefaultStyle(){
cellStyle = null;
} /**
* 创建新行
* @param index 从0开始计数
*/
public void createRow(int index){
//如果在当前插入数据的区域有后续行,则将其后面的行往后移动
if(lastLowNum > initrow && index > 0){
sheet.shiftRows(index + initrow ,lastLowNum + index,1,true,true);
}
currentRow = sheet.createRow(index + initrow);
currentRow.setHeight((short)rowheight);
currentRowIndex = index;
currentcol = initcol;
} /**
* 根据传入的字符串值,在当前行上创建新列
* @param value 列的值(字符串)
*/
public void createCell(String value){
HSSFCell cell = createCell();
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
HSSFCellStyle cstyle = (HSSFCellStyle)confStyles.get(cellStyle);
if(null==cstyle){
cstyle=workbook.createCellStyle();
}
cell.setCellStyle(cstyle);
cstyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("@"));
cell.setCellValue(value);
}
public void createCell(float value){
HSSFCell cell = createCell();
HSSFCellStyle cstyle = (HSSFCellStyle)confStyles.get(cellStyle);
if(null==cstyle){
cstyle=workbook.createCellStyle();
}
cstyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
cell.setCellStyle(cstyle);
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
DecimalFormat df=new DecimalFormat("#0.00");
cell.setCellValue(Double.parseDouble(df.format(value)));
}
public void createCell(double value){
HSSFCell cell = createCell();
HSSFCellStyle cstyle = (HSSFCellStyle)confStyles.get(cellStyle);
if(null==cstyle){
cstyle=workbook.createCellStyle();
}
cstyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
cell.setCellStyle(cstyle);
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
DecimalFormat df=new DecimalFormat("#0.00");
cell.setCellValue(Double.parseDouble(df.format(value)));
}
public void createNumberCell(Integer value){
HSSFCell cell = createCell();
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
cell.setCellValue(value);
}
/**
* 根据传入的日期值,在当前行上创建新列
* 在这种情况下(传入日期),你可以在模板中定义对应列
* 的日期格式,这样可以灵活通过模板来控制输出的日期格式
* @param value 日期
*/
public void createCell(Date value){
HSSFCell cell = createCell();
cell.setCellValue(value);
} /**
* 创建当前行的序列号列,通常在一行的开头便会创建
* 注意要使用这个方法,你必需在创建行之前调用initPageNumber方法
*/
public void createSerialNumCell(){
HSSFCell cell = createCell();
cell.setCellValue(currentRowIndex + num);
} @SuppressWarnings("deprecation")
private HSSFCell createCell(){
HSSFCell cell = currentRow.createCell((short)currentcol++);
HSSFCellStyle style = (HSSFCellStyle)styles.get(new Integer(cell.getCellNum()));
if(style != null){
cell.setCellStyle(style);
} //设置了特定格式
if(cellStyle != null){
HSSFCellStyle ts = (HSSFCellStyle)confStyles.get(cellStyle);
if(ts != null){
cell.setCellStyle(ts);
}
}
return cell;
} /**
* 获取当前HSSFWorkbook的实例
* @return
*/
public HSSFWorkbook getWorkbook(){
return workbook;
} /**
* 获取模板中定义的单元格样式,如果没有定义,则返回空
* @param style 模板定义的样式名称
* @return 模板定义的单元格的样式,如果没有定义则返回空
*/
public HSSFCellStyle getTemplateStyle(String style){
return (HSSFCellStyle)confStyles.get(style);
} /**
* 替换模板中的文本参数
* 参数以“#”开始
* @param props
*/
public void replaceParameters(Properties props){
if(props == null || props.size() == 0){
return;
}
Set propsets = props.entrySet();
Iterator rowit = sheet.rowIterator();
while(rowit.hasNext()){
HSSFRow row = (HSSFRow)rowit.next();
if(row == null) continue;
int cellLength = row.getLastCellNum();
for(int i=0; i<cellLength; i++){
HSSFCell cell = (HSSFCell)row.getCell((short)i);
if(cell == null) continue;
String value = cell.getStringCellValue();
if(value != null && value.indexOf("#") != -1){
for (Iterator iter = propsets.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
value = value.replaceAll("#"+entry.getKey(),(String)entry.getValue());
}
}
cell.setCellValue(value);
}
}
} /**
* 初始化Excel配置
*/
private void initConfig(){
lastLowNum = sheet.getLastRowNum();
Iterator rowit = sheet.rowIterator();
boolean configFinish = false;
while(rowit.hasNext()){
if(configFinish){
break;
}
HSSFRow row = (HSSFRow)rowit.next();
if(row == null) continue;
int cellLength = row.getLastCellNum();
int rownum = row.getRowNum();
for(int i=0; i<cellLength; i++){
HSSFCell cell = (HSSFCell)row.getCell((short)i);
if(cell == null) continue;
String config = cell.getStringCellValue();
if(DATAS.equalsIgnoreCase(config)){
//本行是数据开始行和样式配置行,需要读取相应的配置信息
initrow = row.getRowNum();
rowheight = row.getHeight();
initcol = cell.getCellNum();
configFinish = true;
}
if(configFinish){
readCellStyle(cell);
}
}
}
} /**
* 读取cell的样式
* @param cell
*/
@SuppressWarnings("unchecked")
private void readCellStyle(HSSFCell cell){
HSSFCellStyle style = cell.getCellStyle();
if(style == null) return;
styles.put(new Integer(cell.getCellNum()),style);
} /**
* 读取模板中其它单元格的样式配置
*/
private void readCellStyles(){
Iterator rowit = sheet.rowIterator();
while(rowit.hasNext()){
HSSFRow row = (HSSFRow)rowit.next();
if(row == null) continue;
int cellLength = row.getLastCellNum();
for(int i=0; i<cellLength; i++){
HSSFCell cell = (HSSFCell)row.getCell((short)i);
if(cell == null) continue;
String value = cell.getStringCellValue();
if(value != null && value.indexOf("#STYLE_") != -1){
HSSFCellStyle style = cell.getCellStyle();
if(style == null) continue;
confStyles.put(value.substring(1),style);
//remove it
row.removeCell(cell);
}
}
}
}
public void setValue(int rowNum,int colNum,String value){
HSSFRow row=this.sheet.getRow(rowNum);
HSSFCell cell=row.getCell((short)colNum);
if (cell==null){
cell = row.createCell((short) colNum);
}
cell.setCellValue(value);
}
public void mergedRegion(int rowNum,int colNum,int cols,int rows){
sheet.addMergedRegion(new Region(rowNum,(short)colNum,cols,(short)rows));
}
} ----------------------------------------------------生成xls-------------------------------------------------------------------------- public static void main(String[] args) throws Exception {
String realpath = "E://expFuyou.xls";
StyleExcelTemplate template = StyleExcelTemplate.newInstance(realpath);
String offerName = "AC01_"+DateUtils.formatDate(new Date())+"";
String path = System.getProperty("java.io.tmpdir");
//String ff=path+File.separator+offerName+".xls"; 在项目当中用 需加 File.separator 这个 main 慢方法不需要
String ff=path+offerName+".xls";
int count=0;
template.createRow(count);
template.createCell("序号");
template.createCell("开户行");
template.createCell("扣款人银行账号");
template.createCell("户名");
template.createCell("金额(单位:元)");
template.createCell("企业流水账号");
template.createCell("备注");
template.createCell("手机号");
template.createCell("证件类型");
template.createCell("证件号");
List<Object> l = new ArrayList<Object>();
for (int i = 0; i < 20; i++) {
l.add(i);
}
List<Object> ul = new ArrayList<Object>();
for (int i = 0; i < 20; i++) {
ul.add(i);
}
List<Object> list = new ArrayList<Object>();
list.add(l);
list.add(ul); for (int i = 0; i < list .size(); i++) {
count++;
template.createRow(count);//创建新行
List<Object> arr=(List<Object>) list .get(i);
template.createNumberCell(count);//序号
template.createCell(arr.get(1).toString());
template.createCell(arr.get(2).toString());
template.createCell(arr.get(3).toString());
template.createCell(arr.get(4).toString());
template.createCell(arr.get(5).toString());
template.createCell(arr.get(6).toString());
template.createCell(arr.get(7).toString());
template.createCell(arr.get(8).toString());
template.createCell(arr.get(9).toString());
template.createCell(arr.get(10).toString());
}
FileOutputStream fos=new FileOutputStream(ff);
template.getWorkbook().write(fos);//写入文件
fos.close();
}

java生成xls的更多相关文章

  1. Java生成和操作Excel文件(转载)

    Java生成和操作Excel文件   JAVA EXCEL API:是一开放源码项目,通过它Java开发人员可以读取Excel文件的内容.创建新的Excel文件.更新已经存在的Excel文件.使用该A ...

  2. java生成简单Excel工作薄

    前言: 代码都是建立在实际需求上的,上周做完一个调外部电影券接口的项目,这周产品又要excel表格,大致内容为:券所属影院.图片URL.等信息制作为excel表格,把每次同步过来的数据给他分析. jx ...

  3. java 生成Excel开门篇

    本随笔的Excel所用的poi jar包(3.17版本)链接: https://pan.baidu.com/s/1gaa3dJueja8IraUDYCSLIQ 提取密码: 9xr7 简单实现:两个类: ...

  4. oracle PL/SQL调用Java生成Excel

    现在有个需求,  要求编写oracle存储过程生成Excel文件到指定目录,  但是oracle自己的API貌似不太给力,  所以只能通过另一种更强大的语言来实现了  ——Java.有一个Java框架 ...

  5. java 生成简单word(利用Itext工具),生成简单Excel,以及下载笔记

    1.java 生成简单word(包含图片表格) pom中加入itext 相关依赖 <dependency> <groupId>com.lowagie</groupId&g ...

  6. java导出xls

    package com.spring.mvc.xls; import java.io.File;import java.io.FileInputStream;import java.text.Deci ...

  7. 利用JAVA生成二维码

    本文章整理于慕课网的学习视频<JAVA生成二维码>,如果想看视频内容请移步慕课网. 维基百科上对于二维码的解释. 二维条码是指在一维条码的基础上扩展出另一维具有可读性的条码,使用黑白矩形图 ...

  8. Java生成验证码原理(jsp)

     验证码的作用: 验证码是Completely Automated Public Turing test to tell Computers and Humans Apart(全自动区分计算机和人类的 ...

  9. JAVA生成条形码

    1.下载生成条形码所需要的jar包barcode4j.jar: 2.java生成条形码代码 import java.awt.image.BufferedImage;import java.io.Fil ...

随机推荐

  1. 关于Maven项目pom.xml文件不报错却有红叉的问题

    原因:spring-boot,升级到2.1.5版本,而maven-jar-plugin.version插件默认版本不兼容所以报错,但不影响运行 解决:在<properties></p ...

  2. git 合并多次commit

    如果当前分支提交了多次commit,无法merge到master上,就需要合并多出的几次commit 第一步 查看log: git log 第二步 git rebase -i HEAD~2 对最近的两 ...

  3. flume的一些使用

    一.第一层采集通道的编写 1.第一层采集脚本Source的选择①Source: 数据源在日志文件中! 读取日志中的数据,可以使用以下Source ExecSource: 可以执行一个linux命令,例 ...

  4. Tomca7t服务器 配置HTTP和HTTPS 同时访问

    (首先你要有 ssl 证书 ,我是阿里的 ) 查看申请ssl证书(https://www.cnblogs.com/lxf-mw/p/14261303.html) 一.下载 tomcat证书(两个文件) ...

  5. Ts有限状态机

    ts版本的有限状态机 最近做小游戏要做切换人物状态,花点时间写了一个有限状态机,使用语言为Ts,也可改成自己的语言 按照目前的逻辑,这个可以继续横向扩展,某些做流程管理 先上预览图 Fsm:状态机类 ...

  6. 【Docker】Docker概述、理解docker的集装箱、标准化、隔离的思想、 docker出现解决了什么问题

    整理一下 慕课网 第一个docker化的java应用 Docker环境下的前后端分离项目部署与运维 课程时所做的笔记 Docker概述 docker - https://www.docker.com/ ...

  7. Python eval 函数用途

    Python eval 函数用途: eval 函数可将字符串转换成列表,元组和字典 实例如下: 可以把list,tuple,dict和string相互转化. ##################### ...

  8. 史上最全postgreSQL体系结构(转)

    原文链接:https://cloud.tencent.com/developer/article/1469101 墨墨导读:本文主要从日志文件.参数文件.控制文件.数据文件.redo日志(WAL).后 ...

  9. 使用.net中的API网关模式封装微服务

    在本文中,我们将了解如何使用API网关模式来封装微服务并抽象出底层实现细节,从而允许使用者拥有进入我们系统的一致入口点. 为了构建和测试我们的应用程序,我们需要: 1.Visual Studio 20 ...

  10. Array.of使用实例

    Array.of是es6新增的API,其实粗暴点理解,光看of,就可以猜到它是数组的意思,所以猜测可以用来把字符串转换成数组. 像这样的table,有批量删除和单个删除的功能,,但是又不想写两个方法, ...