描述:工作项目经验。并不是直接生成excel,而是事先已经存在模板,可以在excel中预先设定一些式样,格式。
比如,一些固定的样式。标题等。用于页面显示的数据,后者从数据库中 查询出的数据以excel的形式保存
到银硬盘。
步骤: 1. 预先设置生成的excel的模板,生成,所属等信息。
2. 获取数据。
3. 整理后,给单元格赋值。
4. 生成,打开。
1. 预先设置生成的excel的模板,生成,所属等信息。
public String exportExcel(Wfgm1130Dto wfgs1130Dto, Integer shozokuNo,String printId) throws Exception {
/**VenasPrintDto() 预先设置生成文件的一些必备信息 */
VenasPrintDto printDto = new VenasPrintDto();
setFileName(printId);
printDto.setShozokuNo(shozokuNo); //所属信息
//需要生成的文件的类型 "0"== PDF "1"==Excel "2"==CSV "3"== WORD "4"==XLSM
printDto.setOutputType(OUTPUT_TYPE);
printDto.setOutputFileName(OUTPUT_FILENAME);//生成的文件名字 OUTPUT_FILENAME = "日次入札結果一覧"
printDto.setTemplateFileName(TEMPLATE_FILENAME);//模板的文件名字TEMPLATE_FILENAME = "日次入札結果一覧"
printDto.setSysCodeId(SYSKBN_KEIYAKU);//代表属于哪个功能下的业务 "W"==契约业务
venasPrintDomain.loadSettings(printDto); //下面有介绍该方法
/**
*生成Excel工作簿和sheet页
*①生成Excel工作簿,原理:复制模板文件,打开复制后的模板文件,不改变模板文件
*②通过sheet名获取sheet xlBook.getWrkBook().getSheetName(0)
*/
ExcelWorkBook xlBook = venasPrintDomain.createExcelBookByTempFile(printDto);
ExcelSheet xlSheet = xlBook.item(xlBook.getWrkBook().getSheetName(0));
//要显示的数据源(此处为页面数据)
String gridInfo = wfgs1130Dto.getGridInfo();
JSONAware jsonValue = parseJson(gridInfo);
JSONArray jsonArray = (JSONArray)jsonValue;
//给cell赋值setDaysGridExcel()
xlSheet = setDaysGridExcel(wfgs1130Dto,xlSheet,jsonArray,styleTitleTemp);
// sheet保存
xlBook.save(printDto.getOutputFile().getAbsolutePath());
return printDto.getOutputFile().getName();
}
loadSettings(printDto)方法 作用:
/** 印刷情報設定*/
public void loadSettings(VenasPrintDto dto) throws Exception {
// 设定生成的文件名+时间戳
String outputFileName = dto.getOutputFileName() + "_" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS");
String templateFileName = dto.getTemplateFileName();
String templateFilePath = null;
String outputFilePath = null;
CctlPathDomain.PathId templateFilePathEnvIdFor = null;
CctlPathDomain.PathId outputFilePathEnvIdFor = null;
//依靠getSysCodeId上一步设定的功能区分,判断属于哪个功能
switch (dto.getSysCodeId()) {
case Constants.SYSKBN_HENSEI: break;// 編成
case Constants.SYSKBN_KESSAN:break;// 決算
case Constants.SYSKBN_TOKEI:break; // 統計
case Constants.SYSKBN_SHIKKO:break;// 執行
case Constants.SYSKBN_KEIYAKU: // 契約
// getOutputType判断要生成什么类型文件
switch (dto.getOutputType()) {
case VenasConstants.OUTPUT_TYPE_Excel://Excel文件
templateFilePathEnvIdFor = CctlPathDomain.PathId.EXCEL_Sheet;
outputFilePathEnvIdFor = CctlPathDomain.PathId.EXCEL_Sheet_OUT;
templateFileName += VenasConstants.EXCEL_EXTENSION;
outputFileName += VenasConstants.EXCEL_EXTENSION;
break;
case VenasConstants.OUTPUT_TYPE_Excel_XLSM: break; //XLSM文件
}
break;
}
}
if (null != templateFilePathEnvIdFor) {
//数据库中取出模板文件的存放路径
templateFilePath = cctlPathDomain.findString(dto.getSysCodeId(), templateFilePathEnvIdFor);
}
if (null != outputFilePathEnvIdFor) {
//数据库中取出生成文件的存放路径
outputFilePath = cctlPathDomain.findString(dto.getSysCodeId(), outputFilePathEnvIdFor);
}
if (StringUtils.isNotEmpty(templateFilePath)) {
//通过路径+模板名获取模板文件
dto.setTemplateFile(new File(StrUtils.replaceFolderPath(templateFilePath) + templateFileName));
}
if (StringUtils.isNotEmpty(outputFilePath)) {
//通过路径+文件名获取模文件
dto.setOutputFile(new File(StrUtils.replaceFolderPath(outputFilePath) + outputFileName));
VenasUtils.makeDirectoryIfNeed(dto.getOutputFile());
} else {
throw new FwApplicationException(new FwMessage(errorKey));
}
}
createExcelBookByTempFile(printDto):根据模板文件生成Excel工作簿
public ExcelWorkBook createExcelBookByTempFile(VenasPrintDto dto) throws Exception {
// 模板Excel copy
ExcelUtils.copy(dto.getTemplateFile().getAbsolutePath(),
dto.getOutputFile().getAbsolutePath());
// 打开复制后的文件
return ExcelWorkBook.open(dto.getOutputFile().getAbsolutePath());
}
/**
*为ExcelUtils类中的方法。
*/
//ExcelUtils类中的copy()方法,
public static final void copy(String inPath, String outPath) throws IOException {
File inFile = findExcelFile(inPath); //获取模板文件
if (inFile == null) {
throw new IOException("Excel文件不存在: " + inPath);
}
String outPathWithoutExt = removeExcelExt(outPath);
File outFile = new File(outPathWithoutExt + getExt(inFile.getName()));//创建生成文件
//调用FileUtils工具类的copyFile方法,将inFile模板文件的已经有的内容复制到
//outFile生成文件中。
FileUtils.copyFile(inFile, outFile);
}
//将通过string的路径获取file类型的文件
public static final File findExcelFile(String filePath) {
String pathWithoutExt = removeExcelExt(filePath);
File file = new File(pathWithoutExt + ".xls");
if (file.exists()) {return file;}
file = new File(pathWithoutExt + ".xlsx");
if (file.exists()) {return file;}
file = new File(pathWithoutExt +".xlsm");
if (file.exists()) {return file;}
return null;
}
//去除文件的扩展名
public static final String removeExcelExt(String path) {
if (isExcelFile(path)) {
return path.substring(0, path.lastIndexOf('.'));
} else {
return path;
}
}
//该方法用来判断路径所代表的文件是否是excelw文件。
//原理:通过扩展名来判断".xls",".xlsx",".xlsm"
public static final boolean isExcelFile(String filePath) {
return filePath.endsWith(".xls") ||
filePath.endsWith(".xlsx") ||
filePath.endsWith(".xlsm");
}
2.setDaysGridExcel() 如何将数据源赋值到单元格
private ExcelSheet setDaysDetileGridExcel(Wfgm1130Dto wfgs1130Dto,
ExcelSheet xlSheet, JSONArray jsonArray) {
int iRow = 5;
int borderFirstRow = iRow; // 一覧に罫線を引く先頭行;
int borderLastCol =9; // 一覧に罫線を引く最終列;
for ( int i = 0; i < jsonArray.size(); i++) {
JSONObject json = (JSONObject) jsonArray.get(i);
int iCol = 1;
String nyusatuniti = checkNull(json.get("nyusatuniti"));
if(!yoteikagaku.equals("")){
yoteikagaku = df.format(Integer.parseInt(yoteikagaku));
}
xlSheet.setCellVal(iRow, iCol++,nyusatuniti); //赋值
xlSheet.setCellValStyle(iRow, iCol++, yoteikagaku, style);//赋值同时设置样式
xlSheet.setRowHeight(EXCEL_HIGHT, iRow);//设置行高
iRow++;
}
//设置边框线
CellRangeAddress rng = new CellRangeAddress(borderFirstRow, iRow - 1, 1,
borderLastCol); //获取指定的文件范围
xlSheet.setRngBorderTop(rng, CellStyle.BORDER_THIN); //上边线
xlSheet.setRngBorderBottom(rng, CellStyle.BORDER_THIN); //下边线
xlSheet.setRngBorderLeft(rng, CellStyle.BORDER_THIN); //左边线
xlSheet.setRngBorderRight(rng, CellStyle.BORDER_THIN); //右边线
xlSheet.setRngBorderHorizn(rng, CellStyle.BORDER_THIN); //内侧水平线
xlSheet.setRngBorderVrtical(rng, CellStyle.BORDER_THIN);//内侧垂直线
return xlSheet;
}
3.ExcelSheet工具处理类。
package jp.co.bsnnet.sofia.utils.excel;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Footer;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Header;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.PrintSetup;
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.ss.util.CellRangeAddress;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelSheet {
/** ブック操作クラス */
private Workbook hssfBook = null;
/** ExcelWorkBookクラス */
private ExcelWorkBook xlBook = null;
/** シート操作クラス */
private Sheet hssfSheet = null;
/** ヘッダ */
private Header header;
/** フッタ */
private Footer footer;
/** 印刷 */
private PrintSetup ps;
********************************************************************************************
public void setHssfSheet(Sheet hssfSheet) {
this.hssfSheet = hssfSheet;
this.header = this.hssfSheet.getHeader();
this.footer = this.hssfSheet.getFooter();
this.ps = this.hssfSheet.getPrintSetup();
}
public Sheet getHssfSheet() {
return hssfSheet;
}
public ExcelWorkBook getXlBook() {
return xlBook;
}
public void setXlBook(ExcelWorkBook xlBook) {
this.xlBook = xlBook;
}
// *********************************************************************************************
/**
* コンストラクタ
*
* @param hssfBook
* 自分親となるエクセルブック
*/
// *********************************************************************************************
public ExcelSheet(ExcelWorkBook hssfBook) {
this.xlBook = hssfBook;
this.hssfBook = xlBook.getWrkBook();
}
// ---------------------------------------------------------------------------------------------
//
// シート
//
// ---------------------------------------------------------------------------------------------
// *********************************************************************************************
/**
* ヘッダの左情報設定
*
* @param val
* 設定値
*/
// *********************************************************************************************
public void setHeaderLeft(String val) {
header.setLeft(val);
}
// *********************************************************************************************
/**
* ヘッダの中央情報設定
*
* @param val
* 設定値
*/
// *********************************************************************************************
public void setHeaderCenter(String val) {
header.setCenter(val);
}
// *********************************************************************************************
/**
* ヘッダの右情報設定
*
* @param val
* 設定値
*/
// *********************************************************************************************
public void setHeaderRight(String val) {
header.setRight(val);
}
// *********************************************************************************************
/**
* フッタの左情報設定
*
* @param val
* 設定値
*/
// *********************************************************************************************
public void setFooterLeft(String val) {
footer.setLeft(val);
}
// *********************************************************************************************
/**
* フッタの中央情報設定
*
* @param val
* 設定値
*/
// *********************************************************************************************
public void setFooterCenter(String val) {
footer.setCenter(val);
}
// *********************************************************************************************
/**
* フッタの右情報設定
*
* @param val
* 設定値
*/
// *********************************************************************************************
public void setFooterRight(String val) {
footer.setRight(val);
}
// *********************************************************************************************
/**
* プロテクト(シートの保護)設定
*/
// *********************************************************************************************
public void protectSheet(String pwd) {
hssfSheet.protectSheet(pwd);
}
// *********************************************************************************************
/**
* プロテクト(シートの保護)解除
*/
// *********************************************************************************************
public void unprotectSheet() {
hssfSheet.protectSheet(null);
}
// *********************************************************************************************
/**
* セルの再計算処理
*/
// *********************************************************************************************
public void reCalculate(boolean bol) {
hssfSheet.setForceFormulaRecalculation(bol);
}
// *********************************************************************************************
/**
* 印刷範囲設定
*/
// *********************************************************************************************
public void setPrintArea(String area) {
hssfBook.setPrintArea(hssfBook.getSheetIndex(hssfSheet), area);
}
// *********************************************************************************************
/**
* 印刷方向の指定
*
* @param bol
* true:横、false:縦
*/
// *********************************************************************************************
public void setPrintLandscape(boolean bol) {
ps.setLandscape(true);
}
// *********************************************************************************************
/**
* 印刷タイトル
*/
// *********************************************************************************************
public CellRangeAddress getRepeatingRows() {
return hssfSheet.getRepeatingRows();
}
public void setRepeatingRows(int rowF, int rowT) {
hssfSheet.setRepeatingRows(new CellRangeAddress(rowF - 1, rowT - 1, -1, -1));
}
public CellRangeAddress getRepeatingCols() {
return hssfSheet.getRepeatingColumns();
}
public void setRepeatingCols(int colF, int colT) {
hssfSheet.setRepeatingColumns(new CellRangeAddress(-1, -1, colF - 1, colT - 1));
}
// *********************************************************************************************
/**
* 印刷用紙の設定
*
* @param size
* 用紙サイズ
*/
// *********************************************************************************************
public void setPrintPaperSize(short size) {
ps.setPaperSize(size);
}
// *********************************************************************************************
/**
* 印刷の倍率指定
*
* @param scale
* スケール(例:75→75%)
*/
// *********************************************************************************************
public void setPrintScale(short scale) {
ps.setScale(scale);
}
// *********************************************************************************************
/**
* 印刷範囲を1ページに収める
*/
// *********************************************************************************************
public void setPrintFitSheet() {
hssfSheet.setAutobreaks(true);
ps.setFitHeight((short) 1);
ps.setFitWidth((short) 1);
}
// *********************************************************************************************
/**
* ヘッダー余白
*
* @param margin
* 余白値(0.394=1)
*/
// *********************************************************************************************
public void setPrintHeaderMargin(double margin) {
ps.setHeaderMargin(margin);
}
// *********************************************************************************************
/**
* フッタ余白
*
* @param margin
* 余白値(0.394=1)
*/
// *********************************************************************************************
public void setPrintFooterMargin(double margin) {
ps.setFooterMargin(margin);
}
// *********************************************************************************************
/**
* 改ページ設定
*/
// *********************************************************************************************
public void setRowBreak(int row) {
hssfSheet.setRowBreak(row - 1);
}
/**
* 印刷タイトル(行設定)
*
* ※注意:ExcelWorkBook 側にもあるが、こちらでは各シート毎に個別対応する+スタート位置は 0 からではなく 1 から
*/
public void setPrintTitleRow(int start, int end) {
hssfBook.setRepeatingRowsAndColumns(hssfBook.getSheetIndex(hssfSheet), -1, -1, start - 1, end - 1);
}
// ---------------------------------------------------------------------------------------------
//
// 行
//
// ---------------------------------------------------------------------------------------------
// *********************************************************************************************
/**
* 指定元行の高さを(範囲指定された)指定先にコピーする
*
* @param row
* コピー元の行
* @param rowF
* コピー先の範囲(From)
* @param rowT
* コピー先の範囲(To)
*/
// *********************************************************************************************
public void copyRowHeight(int orgRow, int rowF, int rowT) {
Row xlRowOrg = getRow(orgRow);
for (int row = orgRow; row <= rowT; row++) {
Row xlRow = getRow(row);
xlRow.setHeight(xlRowOrg.getHeight());
}
}
// *********************************************************************************************
/**
* 行の高さを設定する rowの高さはTWIPSという単位で設定。1TWIPSが1/20ポイントに相当する。1ポイントは1/72インチに相
* 当。ちなみに標準の高さは13.5ポイント
*/
// *********************************************************************************************
public void setRowHeight(int width, int row) {
Row xlRow = getRow(row);
xlRow.setHeight((short) (width * 20));
}
// *********************************************************************************************
/**
* 行の高さを設定する(複数範囲) rowの高さはTWIPSという単位で設定。1TWIPSが1/20ポイントに相当する。1ポイントは1/72インチに相
* 当。ちなみに標準の高さは13.5ポイント
*/
// *********************************************************************************************
public void setRowHeight(int width, int rowF, int rowT) {
Row xlRow;
for (int row = rowF; row <= rowT; row++) {
xlRow = getRow(row);
xlRow.setHeight((short) (width * 20));