描述:工作项目经验。并不是直接生成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"==XLSMprintDto.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 copyExcelUtils.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));}}// *********************************************************************************************/*** 指定した行の取得** @param row*            行の指定* @return 行*/// *********************************************************************************************public Row getRow(int row) {Row xlRow = hssfSheet.getRow(row - 1);if (xlRow == null) {// 行オブジェクトの作成xlRow = hssfSheet.createRow(row - 1);}return xlRow;}// *********************************************************************************************/*** 指定行を隠す*/// *********************************************************************************************public void setRowHidden(boolean bol, int row) {Row xlRow = getRow(row);xlRow.setZeroHeight(bol);}// *********************************************************************************************/*** 指定行を隠す(複数行)*/// *********************************************************************************************public void setRowHidden(boolean bol, int rowF, int rowT) {Row xlRow;for (int row = rowF; row <= rowT; row++) {xlRow = getRow(row);xlRow.setZeroHeight(bol);}}// *********************************************************************************************/*** 定義済み行の最大インデックス値を返す** @return 最終行番号*/// *********************************************************************************************public int getLastRowNum() {return hssfSheet.getLastRowNum();}// *********************************************************************************************/*** 行の挿入** @param row*            挿入位置*/// *********************************************************************************************public void insertRow(int row) {int lastRow = getLastRowNum();// 行をシフトhssfSheet.shiftRows(row - 1, lastRow, 1, true, true);hssfSheet.createRow(row - 1);xlBook.notifyRowInsert(this, row, 1);}// *********************************************************************************************/*** 行の挿入** @param rowF*            開始位置* @param rowT*            終了位置*/// *********************************************************************************************public void insertRow(int rowF, int rowT) {int lastRow = getLastRowNum();// 行をシフトhssfSheet.shiftRows(rowF - 1, lastRow, rowT - rowF + 1, true, true);for (int row = rowF - 1; row <= rowT - rowF + 1; row++) {hssfSheet.createRow(row);}xlBook.notifyRowInsert(this, rowF, rowT - rowF);}// *********************************************************************************************/*** 行のスタイルをコピーする* copyRowStyle** @param srcRowIndex コピーされる行のスタイルのインデックス* @param destRowIndex 対象行インデックス* @param data 対象行行のデータ(設定しない場合はnull)* @param startCellIndex 行内のセールインデックスからコピーする(設定しない場合はnull)*/// *********************************************************************************************public void copyRowStyle(int srcRowIndex, int destRowIndex, String[] data, Integer startCellIndex) {Sheet sheet = this.getHssfSheet();ArrayList<CellRangeAddress> mergedRegions = new ArrayList<CellRangeAddress>();Row srcRow = sheet.getRow(srcRowIndex - 1);Row destRow = sheet.getRow(destRowIndex - 1);if(srcRow == null) {return;}if(destRow == null) {//行を追加します。destRow = sheet.createRow(destRowIndex - 1);}int firstCell;int iDelta;if(startCellIndex != null){firstCell = startCellIndex;iDelta = startCellIndex;} else {firstCell = srcRow.getFirstCellNum();iDelta = 1;}destRow.setHeight(srcRow.getHeight());for (int j = firstCell; j <= srcRow.getLastCellNum(); j++) {Cell srcCell = srcRow.getCell(j);Cell destCell = destRow.getCell(j);if (srcCell != null) {if (destCell == null) {destCell = destRow.createCell(j);}//セールデータとスタイルをコピーdestCell.setCellStyle(srcCell.getCellStyle());//データの設定if(data!=null){if((j-iDelta) < data.length){if(data[j-iDelta]!=null) {try{destCell.setCellValue(Double.parseDouble(data[j-iDelta]));} catch(NumberFormatException e) {destCell.setCellValue(data[j-iDelta]);}}}}CellRangeAddress mergedRegion = getMergedRegion(srcRow.getRowNum(), (short)destCell.getColumnIndex());//コピーされる行がメージセールある場合、メージセールを追加する。if(mergedRegion!=null) {if(!mergedRegions.contains(mergedRegion)){if(mergedRegion.getFirstRow() == mergedRegion.getLastRow()){CellRangeAddress newMergedRegion = new CellRangeAddress(destRowIndex-1, destRowIndex-1, mergedRegion.getFirstColumn(),  mergedRegion.getLastColumn());mergedRegions.add(mergedRegion);sheet.addMergedRegion(newMergedRegion);}}}}}}// *********************************************************************************************/*** 空行を追加する関数* addEmptyRow** @param rowIndex セール列番*/// *********************************************************************************************public void addEmptyRow(int rowIndex) {Sheet sheet = this.getHssfSheet();if(sheet.getFirstRowNum() == rowIndex - 2) {return;}Row rowBefore = sheet.getRow(rowIndex - 2);if(rowBefore == null) {return;}Row newRow = sheet.createRow(rowIndex - 1);newRow.setHeight(rowBefore.getHeight());}// *********************************************************************************************/*** メージされてるセルを取得する処理* CellRangeAddress** @param rowNum セール列番* @param cellNum セール行番* @param CellRangeAddress メージエリア*/// *********************************************************************************************private CellRangeAddress getMergedRegion(int rowNum, short cellNum) {Sheet sheet = this.getHssfSheet();for (int i = 0; i < sheet.getNumMergedRegions(); i++) {CellRangeAddress merged = sheet.getMergedRegion(i);if (merged.isInRange(rowNum, cellNum)) {return merged;}}return null;}// *********************************************************************************************/*** 行のデータを設定する* setRowData** @param rowIndex 対象行のインデックス* @param data 設定するデータ*/// *********************************************************************************************public void setRowData(int rowIndex, String[] data) {Sheet sheet = this.getHssfSheet();Row row = sheet.getRow(rowIndex - 1);if(row == null) {return;}for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {Cell cell = row.getCell(j);if (cell != null) {//データの設定if(data!=null){try{cell.setCellValue(Double.parseDouble(data[j-1]));} catch(NumberFormatException e) {cell.setCellValue(data[j-1]);}}}}}// *********************************************************************************************/*** 行の削除(完全ではない!!)<br>* (HSSFSheet の shirtRows が不完全なためか、上にシフトした後、行のスタイル(背景色等)がおかしくなる場合がある* 例えば、2行目を削除する場合、3行目に黄色がついていたとする。その場合、新しい2行目で黄色と白の部分ができていた** @param row*            削除行*/// *********************************************************************************************public void removeRow(int row) {removeRow(row, row);}// *********************************************************************************************/*** 行の削除(完全ではない!!)<br>* (HSSFSheet の shirtRows が不完全なためか、上にシフトした後、行のスタイル(背景色等)がおかしくなる場合がある* 例えば、2行目を削除する場合、3行目に黄色がついていたとする。その場合、新しい2行目で黄色と白の部分ができていた** @param rowF*            開始位置* @param rowT*            終了位置*/// *********************************************************************************************public void removeRow(int rowF, int rowT) {int lastRow = getLastRowNum();int numRow = rowT - rowF + 1;for (int i = 0; i < numRow; i++) {hssfSheet.removeRow(hssfSheet.getRow(rowF + i - 1));}hssfSheet.shiftRows(rowT, lastRow, -numRow, true, true);xlBook.notifyRowRemoval(this, rowF, rowT);}// *********************************************************************************************/*** 行の上下移動** @param rowF*            開始位置* @param rowT*            終了位置* @param rowM*            移動先*/// *********************************************************************************************public void shiftRows(int rowF, int rowT, int rowM) {hssfSheet.shiftRows(rowF - 1, rowT - 1, rowM, true, true);}// *********************************************************************************************/*** 雛形シートよりデータ出力シートに雛形枠をコピーする 注意)結合されたセルは結合が解除されてしまう** @param rowF*            雛形シートのコピー開始位置(行)* @param rowT*            雛形シートのコピー終了位置(行)* @param colF*            雛形シートのコピー開始位置(列)* @param colT*            雛形シートのコピー終了位置(列)* @param xlSheetT*            コピー先のシート* @param outRow*            コピー先の位置(行)*/// *********************************************************************************************public void copyFmtDat(int rowF, int rowT, int colF, int colT, ExcelSheet xlSheetT, int outRow) {Cell xlCellF; // 雛形シートのセルCell xlCellT; // コピー先のセルfor (int col = colF; col <= colT; col++) {for (int row = rowF; row <= rowT; row++) {xlCellF = getCell(row, col);xlCellT = xlSheetT.getCell(outRow - 1 + row, col);// 値を取得switch (xlCellF.getCellType()) {case Cell.CELL_TYPE_BLANK:break;case Cell.CELL_TYPE_BOOLEAN:xlCellT.setCellValue(xlCellF.getBooleanCellValue());break;case Cell.CELL_TYPE_ERROR:xlCellT.setCellValue(xlCellF.getErrorCellValue());break;case Cell.CELL_TYPE_FORMULA:// この部分がないと保存したブックを再読込でエラーになったFormulaEvaluator eval = xlBook.getFactory().createFormulaEvaluator();CellValue val = eval.evaluate(xlCellF);// この部分がないと保存したブックを再読込でエラーになったxlCellT.setCellFormula(val.formatAsString());break;case Cell.CELL_TYPE_NUMERIC:xlCellT.setCellValue(xlCellF.getNumericCellValue());break;case Cell.CELL_TYPE_STRING:xlCellT.setCellValue(xlCellF.getRichStringCellValue());break;default:}// スタイルを取得xlCellT.setCellStyle(xlCellF.getCellStyle());}}}// *********************************************************************************************/*** 雛形シートよりデータ出力シートに雛形枠をコピーする 注意)結合されたセルは結合が解除されてしまう** @param rowF*            雛形シートのコピー開始位置(行)* @param rowT*            雛形シートのコピー終了位置(行)* @param colF*            雛形シートのコピー開始位置(列)* @param colT*            雛形シートのコピー終了位置(列)* @param xlSheetT*            コピー先のシート* @param startRow*            コピー先の位置(行)* @param startCol*            コピー先の位置(列)*/// *********************************************************************************************public void copyTemplateWithStyle(int rowF, int rowT, int colF, int colT, ExcelSheet xlSheetT, int startRow) {int startCol = colF;copyTemplateWithStyle(rowF, rowT, colF, colT, xlSheetT, startRow, startCol);}public void copyTemplateWithStyle(int rowF, int rowT, int colF, int colT, ExcelSheet xlSheetT, int startRow, int startCol) {Cell xlCellF; // 雛形シートのセルCell xlCellT; // コピー先のセルint outRow = startRow;for (int row = rowF; row <= rowT; row++) {int outCol = startCol;for (int col = colF; col <= colT; col++) {xlCellF = getCell(row, col);xlCellT = xlSheetT.getCell(outRow, outCol);// 値を取得switch (xlCellF.getCellType()) {case Cell.CELL_TYPE_BLANK:break;case Cell.CELL_TYPE_BOOLEAN:xlCellT.setCellValue(xlCellF.getBooleanCellValue());break;case Cell.CELL_TYPE_ERROR:xlCellT.setCellValue(xlCellF.getErrorCellValue());break;case Cell.CELL_TYPE_FORMULA:// この部分がないと保存したブックを再読込でエラーになったFormulaEvaluator eval = xlBook.getFactory().createFormulaEvaluator();CellValue val = eval.evaluate(xlCellF);// この部分がないと保存したブックを再読込でエラーになったxlCellT.setCellFormula(val.formatAsString());break;case Cell.CELL_TYPE_NUMERIC:xlCellT.setCellValue(xlCellF.getNumericCellValue());break;case Cell.CELL_TYPE_STRING:xlCellT.setCellValue(xlCellF.getRichStringCellValue());break;default:}// スタイルを取得xlCellT.setCellStyle(xlCellF.getCellStyle());outCol++;}// 行高さ設定short shortRowHeight = getRow(row).getHeight();xlSheetT.getRow(outRow).setHeight(shortRowHeight);outRow++;}}// ---------------------------------------------------------------------------------------------//// 列//// ---------------------------------------------------------------------------------------------// *********************************************************************************************/*** 指定元列の幅を(範囲指定された)指定先にコピーする** @param col*            コピー元の列* @param colF*            コピー先の範囲(From)* @param colT*            コピー先の範囲(To)*/// *********************************************************************************************public void copyColumnWidth(int orgCol, int colF, int colT) {for (int col = colF; col <= colT; col++) {hssfSheet.setColumnWidth(col - 1, hssfSheet.getColumnWidth(orgCol - 1));}}// *********************************************************************************************/*** 列の幅を設定する(単列)* 変更したい列のインデックス番号と幅を指定します。幅は1を指定すると1文字の1/256のサイズになるようです。4文字分の幅にするには* 1024を指定します。(どの文字が基準になっているかは分かりません)。*/// *********************************************************************************************public void setColumnWidth(int width, int col) {hssfSheet.setColumnWidth(col - 1, width * 256);}public void setColumnWidth(int width, int colF, int colT) {for (int col = colF; col <= colT; col++) {hssfSheet.setColumnWidth(col - 1, width * 256);}}// *********************************************************************************************/*** デフォルトの列の幅を指定する* シートを新規に作成した時に、各列の幅のデフォルト値を指定することができます。列の幅は(なぜか)キャラクターの数で指定します。5文字* 分なら5です。1文字の1/256が1単位ではないよう*/// *********************************************************************************************public void setDefaultColumnWidth(int val) {hssfSheet.setDefaultColumnWidth(val);}// *********************************************************************************************/*** 指定列を隠す(単列)*/// *********************************************************************************************public void setColumnHidden(boolean bol, int col) {hssfSheet.setColumnHidden(col - 1, bol);}// *********************************************************************************************/*** 指定列を隠す(複数列)*/// *********************************************************************************************public void setColumnHidden(boolean bol, int colF, int colT) {for (int col = colF; col <= colT; col++) {hssfSheet.setColumnHidden(col - 1, bol);}}// ---------------------------------------------------------------------------------------------//// セル//// ---------------------------------------------------------------------------------------------// *********************************************************************************************/*** 指定したセルの取得** @param row*            行の指定* @param col*            列の指定* @return セル*/// *********************************************************************************************public Cell getCell(int row, int col) {Row xlRow;Cell xlCell;// 行の取得xlRow = getRow(row);// セルの取得xlCell = xlRow.getCell(col - 1);if (xlCell == null) {// セルオブジェクトの作成xlCell = xlRow.createCell(col - 1);}return xlCell;}// *********************************************************************************************/*** 指定のセルのデータ取得<br>* ※セルには、2008/1/1が設定されているが書式で日本語が混じった"平成20年1月1日"とか表示させてい るセルに対しては、通常の* getCellVal では取得できない。そのような場合に当メソッドで日付データ を取得する** @param row* @param col* @return*/// *********************************************************************************************public Object getCellDateVal(int row, int col) {try {Cell xlCell;// 指定のセル取得xlCell = getCell(row, col);return xlCell.getDateCellValue();// エラーがあっても処理を継続} catch (Exception ex) {return null;}}/*** 指定セルのデータ取得 getCellValでは、百分率のセルの値が正しく取得できないため、既存動作を変えないように新たに作成** @return*/public Object getCellValBigDecimal(int row, int col) {Cell xlCell;// 指定のセル取得xlCell = getCell(row, col);int type = xlCell.getCellType();// -----------------------------------------------------------------------------------------// 文字列// -----------------------------------------------------------------------------------------if (type == Cell.CELL_TYPE_STRING) {return xlCell.getRichStringCellValue();}// -----------------------------------------------------------------------------------------// 数値 or 日付// -----------------------------------------------------------------------------------------else if (type == Cell.CELL_TYPE_NUMERIC) {// - 日付// ------------------------------------------------------------------------------if (DateUtil.isCellDateFormatted(xlCell)) {return xlCell.getDateCellValue();}// - 数値// ------------------------------------------------------------------------------return new BigDecimal(String.valueOf(xlCell.getNumericCellValue()));}// -----------------------------------------------------------------------------------------// true・false// -----------------------------------------------------------------------------------------else if (type == Cell.CELL_TYPE_BOOLEAN) {return xlCell.getBooleanCellValue();}// -----------------------------------------------------------------------------------------// 数式のセルを示す値// -----------------------------------------------------------------------------------------else if (type == Cell.CELL_TYPE_FORMULA) {FormulaEvaluator eval = xlBook.getFactory().createFormulaEvaluator();CellValue val = eval.evaluate(xlCell);// Excelの数式の返す結果が文字列のとき、前後に”が付いていたので、これが付かないように修正したif (val.getCellType() == Cell.CELL_TYPE_STRING) {return val.getStringValue();} else {return val.formatAsString();}}// -----------------------------------------------------------------------------------------// ブランク// -----------------------------------------------------------------------------------------else if (type == Cell.CELL_TYPE_BLANK) {return null;}// -----------------------------------------------------------------------------------------// その他// -----------------------------------------------------------------------------------------else {return xlCell.getRichStringCellValue();}}// *********************************************************************************************/*** 指定のセルのデータ取得** @param row* @param col* @return*/// *********************************************************************************************public Object getCellVal(int row, int col) {Cell xlCell;// 指定のセル取得xlCell = getCell(row, col);int type = xlCell.getCellType();// -----------------------------------------------------------------------------------------// 文字列// -----------------------------------------------------------------------------------------if (type == Cell.CELL_TYPE_STRING) {return xlCell.getRichStringCellValue();}// -----------------------------------------------------------------------------------------// 数値 or 日付// -----------------------------------------------------------------------------------------else if (type == Cell.CELL_TYPE_NUMERIC) {// - 日付// ------------------------------------------------------------------------------if (DateUtil.isCellDateFormatted(xlCell)) {return xlCell.getDateCellValue();}// - 数値// ------------------------------------------------------------------------------return new BigDecimal(xlCell.getNumericCellValue());}// -----------------------------------------------------------------------------------------// true・false// -----------------------------------------------------------------------------------------else if (type == Cell.CELL_TYPE_BOOLEAN) {return xlCell.getBooleanCellValue();}// -----------------------------------------------------------------------------------------// 数式のセルを示す値// -----------------------------------------------------------------------------------------else if (type == Cell.CELL_TYPE_FORMULA) {FormulaEvaluator eval = xlBook.getFactory().createFormulaEvaluator();CellValue val = eval.evaluate(xlCell);// Excelの数式の返す結果が文字列のとき、前後に”が付いていたので、これが付かないように修正したif (val.getCellType() == Cell.CELL_TYPE_STRING) {return val.getStringValue();} else {return val.formatAsString();}}// -----------------------------------------------------------------------------------------// ブランク// -----------------------------------------------------------------------------------------else if (type == Cell.CELL_TYPE_BLANK) {return null;}// -----------------------------------------------------------------------------------------// エラー// -----------------------------------------------------------------------------------------else if (type == Cell.CELL_TYPE_ERROR) {return null;}// -----------------------------------------------------------------------------------------// その他// -----------------------------------------------------------------------------------------else {return xlCell.getRichStringCellValue();}}// *********************************************************************************************/*** 数式セルの場合に数式を取得** @param row* @param col* @return*/// *********************************************************************************************public Object getCellFormula(int row, int col) {Cell xlCell;// 指定のセル取得xlCell = getCell(row, col);int type = xlCell.getCellType();// 数式以外ではなにもしないif (type != Cell.CELL_TYPE_FORMULA) {return null;}return xlCell.getCellFormula();}/*** 指定行のセルに値を設定する。** @param row 行番号* @param startCol 値の設定を開始する列番号* @param values 設定する値*/public void setCellValues(int row, int startCol, Object...values) {for (int i = 0; i < values.length; i++) {Object val = values[i];setCellValCommon(row, startCol + i, val);}}// *********************************************************************************************/*** 指定セルへ値を設定** @param row* @param col* @return*/// *********************************************************************************************public void setCellValCommon(int row, int col, Object val) {if (val != null) {if (val instanceof String) {this.setCellVal(row, col, (String) val);} else if (val instanceof Double) {this.setCellVal(row, col, (Double) val);} else if (val instanceof Long) {this.setCellVal(row, col, (Long) val);} else if (val instanceof Integer) {this.setCellVal(row, col, (Integer) val);} else if (val instanceof Calendar) {this.setCellVal(row, col, (Calendar) val);} else if (val instanceof Date) {this.setCellVal(row, col, (Date) val);} else if (val instanceof Boolean) {this.setCellVal(row, col, (Boolean) val);} else {this.setCellVal(row, col, val.toString());}} else {this.setCellVal(row, col, "");}}// *********************************************************************************************/*** 指定セルへ値を設定** @param row* @param col* @return*/// *********************************************************************************************public void setCellVal(int row, int col, String val) {try {Cell xlCell = getCell(row, col);// 日本語を含む場合のエンコーディングxlCell.setCellValue(xlBook.getFactory().createRichTextString(val));// エラーがあっても処理を継続} catch (Exception ex) {;}}// *********************************************************************************************/*** 指定セルへ値とstyleを設定** @param row* @param col* @param val* @param style* @return*/// *********************************************************************************************public void setCellValStyle(int row, int col, String val,CellStyle style) {try {Cell xlCell = getCell(row, col);// 日本語を含む場合のエンコーディングxlCell.setCellValue(xlBook.getFactory().createRichTextString(val));xlCell.setCellStyle(style);// エラーがあっても処理を継続} catch (Exception ex) {;}}public void setCellVal(int row, int col, double val) {try {Cell xlCell = getCell(row, col);xlCell.setCellValue(val);// エラーがあっても処理を継続} catch (Exception ex) {;}}public void setCellVal(int row, int col, Calendar val) {try {Cell xlCell = getCell(row, col);xlCell.setCellValue(val);// エラーがあっても処理を継続} catch (Exception ex) {;}}public void setCellVal(int row, int col, Date val) {try {Cell xlCell = getCell(row, col);xlCell.setCellValue(val);// エラーがあっても処理を継続} catch (Exception ex) {;}}public void setCellVal(int row, int col, boolean val) {try {Cell xlCell = getCell(row, col);xlCell.setCellValue(val);// エラーがあっても処理を継続} catch (Exception ex) {;}}public void setCellFormula(int row, int col, String val) {try {Cell xlCell = getCell(row, col);if (xlCell.getCellType() != Cell.CELL_TYPE_FORMULA) {xlCell.setCellType(Cell.CELL_TYPE_FORMULA);}xlCell.setCellFormula(val);// エラーがあっても処理を継続} catch (Exception ex) {;}}// *********************************************************************************************/*** 指定範囲内のセルにスタイルを設定** @param rowF*            開始位置(行)* @param rowT*            終了位置(行)* @param colF*            開始位置(列)* @param colT*            終了位置(列)* @param color*            色*/// *********************************************************************************************public void setRngStyle(int rowF, int rowT, int colF, int colT, CellStyle style) {Cell xlCell = null;for (int col = colF; col <= colT; col++) {for (int row = rowF; row <= rowT; row++) {xlCell = getCell(row, col);xlCell.setCellStyle(style);}}}// *********************************************************************************************/*** 複数セルに対して書式を一度に設定する** @param rowF*            firstRow (行)* @param rowT*            lastRow (行)* @param colF*            firstCol (列)* @param colT*            lastCol (列)*/// *********************************************************************************************public void setRngDatFmt(int rowF, int rowT, int colF, int colT, String fmt) {if (xlBook.isMemorySavingMode()) {// 省メモリモードのときは、セルスタイルの更新を後で一度に行う。short format = xlBook.getFactory().getDataFormat().getFormat(fmt);CellStyleUpdate update = getXlBook().findUpdate(CellStyleProperty.dataFormat, format);update.addCell(this, rowF, rowT, colF, colT);return;}CellStyle stylePrev = null; // 前回セルのスタイル(今回の色設定前)CellStyle styleCurr = null; // 現在セルのスタイル(今回の色設定前)CellStyle style = null; // 今回設定するスタイルCell xlCell;DataFormat format = hssfBook.createDataFormat();for (int col = colF; col <= colT; col++) {for (int row = rowF; row <= rowT; row++) {xlCell = getCell(row, col);// スタイル設定前の情報を保持styleCurr = xlCell.getCellStyle();// 前セルと今回セルで同じスタイルなら次if (styleCurr.equals(stylePrev)) {// 前回作成したスタイルをそのまま使用xlCell.setCellStyle(style);continue;}// 前セルの設定stylePrev = xlCell.getCellStyle();// 現在設定されているスタイルに今回スタイル設定を加えるstyle = hssfBook.createCellStyle();style.cloneStyleFrom(xlCell.getCellStyle());// style.setDataFormat(HSSFDataFormat.getBuiltinFormat(fmt));style.setDataFormat(format.getFormat(fmt));xlCell.setCellStyle(style);}}}// *********************************************************************************************/*** 指定した範囲のセルの結合** @param rowF*            firstRow (行)* @param rowT*            lastRow (行)* @param colF*            firstCol (列)* @param colT*            lastCol (列)*/// *********************************************************************************************public void mergeCell(int rowF, int rowT, int colF, int colT) {hssfSheet.addMergedRegion(new CellRangeAddress(rowF - 1, rowT - 1, colF - 1, colT - 1));}// *********************************************************************************************/*** 指定したセルへ画像貼り付け** @param row*            画像貼り付け開始位置 (行)* @param col*            画像貼り付け開始位置 (列)* @param byteArrayOut*            画像データ*/// *********************************************************************************************public void setImage(int row, int col, ByteArrayOutputStream byteArrayOut) {Drawing drawing = hssfSheet.createDrawingPatriarch();ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 0, 0, 0);// 画像描画位置指定anchor.setCol1(col);anchor.setRow1(row);anchor.setAnchorType(0);int picIndex = hssfBook.addPicture(byteArrayOut.toByteArray(), Workbook.PICTURE_TYPE_PNG);Picture pic = drawing.createPicture(anchor, picIndex);pic.resize();}// *********************************************************************************************/*** 指定セルへの色設定** @param row* @param col* @return*/// *********************************************************************************************public void setCellColor(int row, int col, short color) {setRngColor(row, row, col, col, color);}// *********************************************************************************************/*** 指定範囲内のセルに対してまとめて色を設定** @param rowF*            開始位置(行)* @param rowT*            終了位置(行)* @param colF*            開始位置(列)* @param colT*            終了位置(列)* @param color*            色*/// *********************************************************************************************public void setRngColor(int rowF, int rowT, int colF, int colT, short color) {if (xlBook.isMemorySavingMode()) {// 省メモリモードのときは、セルスタイルの更新を後で一度に行う。CellStyleUpdate update = getXlBook().findUpdate(CellStyleProperty.fillForegroundColor, color,CellStyleProperty.fillPattern, CellStyle.SOLID_FOREGROUND);update.addCell(this, rowF, rowT, colF, colT);return;}CellStyle stylePrev = null; // 前回セルのスタイル(今回の色設定前)CellStyle styleCurr = null; // 現在セルのスタイル(今回の色設定前)CellStyle style = null; // 今回設定するスタイルCell xlCell = null;for (int col = colF; col <= colT; col++) {for (int row = rowF; row <= rowT; row++) {xlCell = getCell(row, col);// スタイル設定前の情報を保持styleCurr = xlCell.getCellStyle();// 前セルと今回セルで同じスタイルなら次if (styleCurr.equals(stylePrev)) {// 前回作成したスタイルをそのまま使用xlCell.setCellStyle(style);continue;}// 前セルの設定stylePrev = xlCell.getCellStyle();// 現在設定されているスタイルに今回スタイル設定を加えるstyle = hssfBook.createCellStyle();style.cloneStyleFrom(xlCell.getCellStyle()); // 既存スタイルのコピーstyle.setFillForegroundColor(color); // 背景色を設定style.setFillPattern(CellStyle.SOLID_FOREGROUND); // 塗りつぶしパターンを設定xlCell.setCellStyle(style);}}}// private HSSFCellStyle cp(HSSFCell xlCell) {// HSSFCellStyle style;// HSSFCellStyle styleBak;//// styleBak = xlCell.getCellStyle();//// style = xlBook.createCellStyle(); //新スタイル作成//// //バックアップからの戻し//// style.setAlignment (styleBak.getAlignment());// style.setBorderBottom (styleBak.getBorderBottom());// style.setBorderLeft (styleBak.getBorderLeft());// style.setBorderRight (styleBak.getBorderRight());// style.setBorderTop (styleBak.getBorderTop());// style.setBottomBorderColor (styleBak.getBottomBorderColor());// style.setDataFormat (styleBak.getDataFormat());// style.setFillBackgroundColor(styleBak.getFillBackgroundColor());// style.setFillForegroundColor(styleBak.getFillForegroundColor());// style.setFillPattern (styleBak.getFillPattern());// style.setFont (styleBak.getFont(xlBook));// style.setHidden (styleBak.getHidden());// style.setIndention (styleBak.getIndention());// style.setLeftBorderColor (styleBak.getLeftBorderColor());// style.setLocked (styleBak.getLocked());// style.setRightBorderColor (styleBak.getRightBorderColor());// style.setRotation (styleBak.getRotation());// style.setTopBorderColor (styleBak.getTopBorderColor());// // style.setUserStyleName (styleBak.getUserStyleName());// style.setVerticalAlignment (styleBak.getVerticalAlignment());// style.setWrapText (styleBak.getWrapText());//// return style;// }// *********************************************************************************************/*** 指定範囲内のセルに対してまとめてフォントを設定** @param rowF*            開始位置(行)* @param rowT*            終了位置(行)* @param colF*            開始位置(列)* @param colT*            終了位置(列)* @param font*            フォント*/// *********************************************************************************************public void setRngFont(int rowF, int rowT, int colF, int colT, Font font) {if (xlBook.isMemorySavingMode()) {// 省メモリモードのときは、セルスタイルの更新を後で一度に行う。CellStyleUpdate update = getXlBook().findUpdate(CellStyleProperty.fontIndex, font.getIndex());update.addCell(this, rowF, rowT, colF, colT);return;}CellStyle stylePrev = null; // 前回セルのスタイル(今回の色設定前)CellStyle styleCurr = null; // 現在セルのスタイル(今回の色設定前)CellStyle style = null; // 今回設定するスタイルCell xlCell = null;for (int col = colF; col <= colT; col++) {for (int row = rowF; row <= rowT; row++) {xlCell = getCell(row, col);// スタイル設定前の情報を保持styleCurr = xlCell.getCellStyle();// 前セルと今回セルで同じスタイルなら次if (styleCurr.equals(stylePrev)) {// 前回作成したスタイルをそのまま使用xlCell.setCellStyle(style);continue;}// 前セルの設定stylePrev = xlCell.getCellStyle();// 現在設定されているスタイルに今回スタイル設定を加えるstyle = hssfBook.createCellStyle();style.cloneStyleFrom(xlCell.getCellStyle()); // 既存スタイルのコピーstyle.setFont(font);xlCell.setCellStyle(style);}}}// *********************************************************************************************/*** 指定範囲内のセルに対してまとめて文字位置を設定** @param rowF*            開始位置(行)* @param rowT*            終了位置(行)* @param colF*            開始位置(列)* @param colT*            終了位置(列)* @param font*            フォント*/// *********************************************************************************************public void setRngAlignment(int rowF, int rowT, int colF, int colT, short alignment) {if (xlBook.isMemorySavingMode()) {// 省メモリモードのときは、セルスタイルの更新を後で一度に行う。CellStyleUpdate update = getXlBook().findUpdate(CellStyleProperty.alignment, alignment);update.addCell(this, rowF, rowT, colF, colT);return;}CellStyle stylePrev = null; // 前回セルのスタイルCellStyle styleCurr = null; // 現在セルのスタイルCellStyle style = null; // 今回設定するスタイルCell xlCell = null;for (int col = colF; col <= colT; col++) {for (int row = rowF; row <= rowT; row++) {xlCell = getCell(row, col);// スタイル設定前の情報を保持styleCurr = xlCell.getCellStyle();// 前セルと今回セルで同じスタイルなら次if (styleCurr.equals(stylePrev)) {// 前回作成したスタイルをそのまま使用xlCell.setCellStyle(style);continue;}// 前セルの設定stylePrev = xlCell.getCellStyle();// 現在設定されているスタイルに今回スタイル設定を加えるstyle = hssfBook.createCellStyle();style.cloneStyleFrom(xlCell.getCellStyle()); // 既存スタイルのコピーstyle.setAlignment(alignment);xlCell.setCellStyle(style);}}}// *********************************************************************************************/*** 複数セルに対してまとめて罫線を引く(Top)<br>* 外部から色を指定しない場合は、デフォルト黒で設定する** @param rng*            範囲* @param borderStyle*            罫線のスタイル*/// *********************************************************************************************public void setRngBorderTop(CellRangeAddress inRng, short borderStyle) {// デフォルトの色を黒にする(罫線を引いた時に色を指定しないと Excel を開いた時に// 「セルの書式設定」ダイアログが起動できなくなるため必ず色を指定する)setRngBorderTop(inRng, borderStyle, IndexedColors.BLACK.getIndex());}// *********************************************************************************************/*** 複数セルに対してまとめて罫線を引く(Top)** @param rng*            範囲* @param borderStyle*            罫線のスタイル* @param color*            色*/// *********************************************************************************************public void setRngBorderTop(CellRangeAddress inRng, short borderStyle, short color) {// int rowF = inRng.getFirstRow() -1;// int rowT = inRng.getLastRow() -1;// int colF = inRng.getFirstColumn() -1;// int colT = inRng.getLastColumn() -1;//// CellRangeAddress rng = new CellRangeAddress(rowF,rowT,colF,colT);//// HSSFRegionUtil.setBorderTop(borderStyle, rng, hssfSheet,hssfBook);// ※HSSFRegionUtil は、罫線が正しく引けない+セルの書式が変更できなくなる問題があるため使用しないif (xlBook.isMemorySavingMode()) {// 省メモリモードのときは、セルスタイルの更新を後で一度に行う。int rowF = inRng.getFirstRow();int rowT = inRng.getLastRow();int colF = inRng.getFirstColumn();int colT = inRng.getLastColumn();CellStyleUpdate update = getXlBook().findUpdate(CellStyleProperty.borderTop, borderStyle,CellStyleProperty.topBorderColor, color);update.addCell(this, rowF, rowT, colF, colT);return;}CellStyle stylePrev = null; // 前回セルのスタイル(今回の色設定前)CellStyle styleCurr = null; // 現在セルのスタイル(今回の色設定前)CellStyle style = null; // 今回設定するスタイルCell xlCell = null;int rowF = inRng.getFirstRow();int colF = inRng.getFirstColumn();int colT = inRng.getLastColumn();// 指定の範囲で罫線を設定するfor (int col = colF; col <= colT; col++) {xlCell = getCell(rowF, col);// スタイル設定前の情報を保持styleCurr = xlCell.getCellStyle();// 前セルと今回セルで同じスタイルなら次if (styleCurr.equals(stylePrev)) {// 前回作成したスタイルをそのまま使用xlCell.setCellStyle(style);continue;}// 前セルの設定stylePrev = xlCell.getCellStyle();// 現在設定されているスタイルに今回スタイル設定を加えるstyle = hssfBook.createCellStyle(); // 新スタイル作成style.cloneStyleFrom(xlCell.getCellStyle()); // 設定済スタイルのコピー// 線の色の設定style.setTopBorderColor(color);// 線の設定style.setBorderTop(borderStyle);// スタイル適用xlCell.setCellStyle(style);}}// *********************************************************************************************/*** 複数セルに対してまとめて罫線を引く(Bottom)<br>* 外部から色を指定しない場合は、デフォルト黒で設定する** @param rng*            範囲* @param borderStyle*            罫線のスタイル*/// *********************************************************************************************public void setRngBorderBottom(CellRangeAddress inRng, short borderStyle) {// デフォルトの色を黒にする(罫線を引いた時に色を指定しないと Excel を開いた時に// 「セルの書式設定」ダイアログが起動できなくなるため必ず色を指定する)setRngBorderBottom(inRng, borderStyle, IndexedColors.BLACK.getIndex());}// *********************************************************************************************/*** 複数セルに対してまとめて罫線を引く(Bottom)** @param borderStyle*            罫線のスタイル* @param rng*            範囲*/// *********************************************************************************************public void setRngBorderBottom(CellRangeAddress inRng, short borderStyle, short color) {// int rowF = inRng.getFirstRow() -1;// int rowT = inRng.getLastRow() -1;// int colF = inRng.getFirstColumn() -1;// int colT = inRng.getLastColumn() -1;//// CellRangeAddress rng = new CellRangeAddress(rowF,rowT,colF,colT);//// HSSFRegionUtil.setBorderBottom(borderStyle, rng, hssfSheet,hssfBook);// ※HSSFRegionUtil は、罫線が正しく引けない+セルの書式が変更できなくなる問題があるため使用しないif (xlBook.isMemorySavingMode()) {// 省メモリモードのときは、セルスタイルの更新を後で一度に行う。int rowF = inRng.getFirstRow();int rowT = inRng.getLastRow();int colF = inRng.getFirstColumn();int colT = inRng.getLastColumn();CellStyleUpdate update = getXlBook().findUpdate(CellStyleProperty.borderBottom, borderStyle,CellStyleProperty.bottomBorderColor, color);update.addCell(this, rowF, rowT, colF, colT);return;}CellStyle stylePrev = null; // 前回セルのスタイル(今回の色設定前)CellStyle styleCurr = null; // 現在セルのスタイル(今回の色設定前)CellStyle style = null;Cell xlCell = null;int rowT = inRng.getLastRow();int colF = inRng.getFirstColumn();int colT = inRng.getLastColumn();// 指定の範囲で罫線を設定するfor (int col = colF; col <= colT; col++) {xlCell = getCell(rowT, col);// スタイル設定前の情報を保持styleCurr = xlCell.getCellStyle();// 前セルと今回セルで同じスタイルなら次if (styleCurr.equals(stylePrev)) {// 前回作成したスタイルをそのまま使用xlCell.setCellStyle(style);continue;}// 前セルの設定stylePrev = xlCell.getCellStyle();// 現在設定されているスタイルに今回スタイル設定を加えるstyle = hssfBook.createCellStyle(); // 新スタイル作成style.cloneStyleFrom(xlCell.getCellStyle()); // 設定済スタイルのコピー// 線の色の設定style.setBottomBorderColor(color);// 線の設定style.setBorderBottom(borderStyle);// スタイル適用xlCell.setCellStyle(style);}}// *********************************************************************************************/*** 複数セルに対してまとめて罫線を引く(Left)<br>* 外部から色を指定しない場合は、デフォルト黒で設定する** @param rng*            範囲* @param borderStyle*            罫線のスタイル*/// *********************************************************************************************public void setRngBorderLeft(CellRangeAddress inRng, short borderStyle) {// デフォルトの色を黒にする(罫線を引いた時に色を指定しないと Excel を開いた時に// 「セルの書式設定」ダイアログが起動できなくなるため必ず色を指定する)setRngBorderLeft(inRng, borderStyle, IndexedColors.BLACK.getIndex());}// *********************************************************************************************/*** 複数セルに対してまとめて罫線を引く(Left)** @param borderStyle*            罫線のスタイル* @param rng*            範囲*/// *********************************************************************************************public void setRngBorderLeft(CellRangeAddress inRng, short borderStyle, short color) {// int rowF = inRng.getFirstRow() -1;// int rowT = inRng.getLastRow() -1;// int colF = inRng.getFirstColumn() -1;// int colT = inRng.getLastColumn() -1;//// CellRangeAddress rng = new CellRangeAddress(rowF,rowT,colF,colT);//// HSSFRegionUtil.setBorderLeft(borderStyle, rng, hssfSheet,hssfBook);// ※HSSFRegionUtil は、罫線が正しく引けない+セルの書式が変更できなくなる問題があるため使用しないif (xlBook.isMemorySavingMode()) {// 省メモリモードのときは、セルスタイルの更新を後で一度に行う。int rowF = inRng.getFirstRow();int rowT = inRng.getLastRow();int colF = inRng.getFirstColumn();int colT = inRng.getLastColumn();CellStyleUpdate update = getXlBook().findUpdate(CellStyleProperty.borderLeft, borderStyle,CellStyleProperty.leftBorderColor, color);update.addCell(this, rowF, rowT, colF, colT);return;}CellStyle stylePrev = null; // 前回セルのスタイル(今回の色設定前)CellStyle styleCurr = null; // 現在セルのスタイル(今回の色設定前)CellStyle style = null; // 今回設定するスタイルCell xlCell = null;int rowF = inRng.getFirstRow();int rowT = inRng.getLastRow();int colF = inRng.getFirstColumn();// 指定の範囲で罫線を設定するfor (int row = rowF; row <= rowT; row++) {xlCell = getCell(row, colF);// スタイル設定前の情報を保持styleCurr = xlCell.getCellStyle();// 前セルと今回セルで同じスタイルなら次if (styleCurr.equals(stylePrev)) {// 前回作成したスタイルをそのまま使用xlCell.setCellStyle(style);continue;}// 前セルの設定stylePrev = xlCell.getCellStyle();// 現在設定されているスタイルに今回スタイル設定を加えるstyle = hssfBook.createCellStyle(); // 新スタイル作成style.cloneStyleFrom(xlCell.getCellStyle()); // 設定済スタイルのコピー// 線の色の設定style.setLeftBorderColor(color);// 線の設定style.setBorderLeft(borderStyle);// スタイル適用xlCell.setCellStyle(style);}}// *********************************************************************************************/*** 複数セルに対してまとめて罫線を引く(Right)<br>* 外部から色を指定しない場合は、デフォルト黒で設定する** @param rng*            範囲* @param borderStyle*            罫線のスタイル*/// *********************************************************************************************public void setRngBorderRight(CellRangeAddress inRng, short borderStyle) {// デフォルトの色を黒にする(罫線を引いた時に色を指定しないと Excel を開いた時に// 「セルの書式設定」ダイアログが起動できなくなるため必ず色を指定する)setRngBorderRight(inRng, borderStyle, IndexedColors.BLACK.getIndex());}// *********************************************************************************************/*** 複数セルに対してまとめて罫線を引く(Right)** @param borderStyle*            罫線のスタイル* @param rng*            範囲*/// *********************************************************************************************public void setRngBorderRight(CellRangeAddress inRng, short borderStyle, short color) {// int rowF = inRng.getFirstRow() -1;// int rowT = inRng.getLastRow() -1;// int colF = inRng.getFirstColumn() -1;// int colT = inRng.getLastColumn() -1;//// CellRangeAddress rng = new CellRangeAddress(rowF,rowT,colF,colT);//// HSSFRegionUtil.setBorderRight(borderStyle, rng, hssfSheet,hssfBook);// ※HSSFRegionUtil は、罫線が正しく引けない+セルの書式が変更できなくなる問題があるため使用しないif (xlBook.isMemorySavingMode()) {// 省メモリモードのときは、セルスタイルの更新を後で一度に行う。int rowF = inRng.getFirstRow();int rowT = inRng.getLastRow();int colF = inRng.getFirstColumn();int colT = inRng.getLastColumn();CellStyleUpdate update = getXlBook().findUpdate(CellStyleProperty.borderRight, borderStyle,CellStyleProperty.rightBorderColor, color);update.addCell(this, rowF, rowT, colF, colT);return;}CellStyle stylePrev = null; // 前回セルのスタイル(今回の色設定前)CellStyle styleCurr = null; // 現在セルのスタイル(今回の色設定前)CellStyle style = null; // 今回設定するスタイルCell xlCell = null;int rowF = inRng.getFirstRow();int rowT = inRng.getLastRow();int colT = inRng.getLastColumn();// 指定の範囲で罫線を設定するfor (int row = rowF; row <= rowT; row++) {xlCell = getCell(row, colT);// スタイル設定前の情報を保持styleCurr = xlCell.getCellStyle();// 前セルと今回セルで同じスタイルなら次if (styleCurr.equals(stylePrev)) {// 前回作成したスタイルをそのまま使用xlCell.setCellStyle(style);continue;}// 前セルの設定stylePrev = xlCell.getCellStyle();// 現在設定されているスタイルに今回スタイル設定を加えるstyle = hssfBook.createCellStyle(); // 新スタイル作成style.cloneStyleFrom(xlCell.getCellStyle()); // 設定済スタイルのコピー// 線の色の設定style.setRightBorderColor(color);// 線の設定style.setBorderRight(borderStyle);// スタイル適用xlCell.setCellStyle(style);}}// *********************************************************************************************/*** 複数セルに対してまとめて罫線を引く(内側水平線)<br>* 外部から色を指定しない場合は、デフォルト黒で設定する** @param rng*            範囲* @param borderStyle*            罫線のスタイル*/// *********************************************************************************************public void setRngBorderHorizn(CellRangeAddress inRng, short borderStyle) {// デフォルトの色を黒にする(罫線を引いた時に色を指定しないと Excel を開いた時に// 「セルの書式設定」ダイアログが起動できなくなるため必ず色を指定する)setRngBorderHorizn(inRng, borderStyle, IndexedColors.BLACK.getIndex());}// *********************************************************************************************/*** 複数セルに対してまとめて罫線を引く(内側水平線)** @param borderStyle*            罫線のスタイル* @param rng*            範囲*/// *********************************************************************************************public void setRngBorderHorizn(CellRangeAddress inRng, short borderStyle, short color) {if (xlBook.isMemorySavingMode()) {// 省メモリモードのときは、セルスタイルの更新を後で一度に行う。int rowF = inRng.getFirstRow();int rowT = inRng.getLastRow();int colF = inRng.getFirstColumn();int colT = inRng.getLastColumn();CellStyleUpdate update = getXlBook().findUpdate(CellStyleProperty.borderBottom, borderStyle,CellStyleProperty.bottomBorderColor, color);update.addCell(this, rowF, rowT, colF, colT);return;}CellStyle stylePrev = null; // 前回セルのスタイル(今回の色設定前)CellStyle styleCurr = null; // 現在セルのスタイル(今回の色設定前)CellStyle style = null; // 今回設定するスタイルCell xlCell = null;int rowF = inRng.getFirstRow();int rowT = inRng.getLastRow();int colF = inRng.getFirstColumn();int colT = inRng.getLastColumn();// 内側に線を引くセルが無いif (rowF >= rowT) {return;}for (int col = colF; col <= colT; col++) {for (int row = rowF; row < rowT; row++) {xlCell = getCell(row, col);// スタイル設定前の情報を保持styleCurr = xlCell.getCellStyle();// 前セルと今回セルで同じスタイルなら次if (styleCurr.equals(stylePrev)) {// 前回作成したスタイルをそのまま使用xlCell.setCellStyle(style);continue;}// 前セルの設定stylePrev = xlCell.getCellStyle();// 現在設定されているスタイルに今回スタイル設定を加えるstyle = hssfBook.createCellStyle(); // 新スタイル作成style.cloneStyleFrom(xlCell.getCellStyle()); // 設定済スタイルのコピー// 線の色の設定style.setBottomBorderColor(color);// 線の設定style.setBorderBottom(borderStyle);// スタイル適用xlCell.setCellStyle(style);}}}// *********************************************************************************************/*** 複数セルに対してまとめて罫線を引く(内側垂直線)<br>* 外部から色を指定しない場合は、デフォルト黒で設定する** @param rng*            範囲* @param borderStyle*            罫線のスタイル*/// *********************************************************************************************public void setRngBorderVrtical(CellRangeAddress inRng, short borderStyle) {// デフォルトの色を黒にする(罫線を引いた時に色を指定しないと Excel を開いた時に// 「セルの書式設定」ダイアログが起動できなくなるため必ず色を指定する)setRngBorderVrtical(inRng, borderStyle, IndexedColors.BLACK.getIndex());}// *********************************************************************************************/*** 複数セルに対してまとめて罫線を引く(内側垂直線)** @param borderStyle*            罫線のスタイル* @param rng*            範囲*/// *********************************************************************************************public void setRngBorderVrtical(CellRangeAddress inRng, short borderStyle, short color) {if (xlBook.isMemorySavingMode()) {// 省メモリモードのときは、セルスタイルの更新を後で一度に行う。int rowF = inRng.getFirstRow();int rowT = inRng.getLastRow();int colF = inRng.getFirstColumn();int colT = inRng.getLastColumn();CellStyleUpdate update = getXlBook().findUpdate(CellStyleProperty.borderRight, borderStyle,CellStyleProperty.rightBorderColor, color);update.addCell(this, rowF, rowT, colF, colT);return;}CellStyle stylePrev = null; // 前回セルのスタイル(今回の色設定前)CellStyle styleCurr = null; // 現在セルのスタイル(今回の色設定前)CellStyle style = null; // 今回設定するスタイルCell xlCell = null;int rowF = inRng.getFirstRow();int rowT = inRng.getLastRow();int colF = inRng.getFirstColumn();int colT = inRng.getLastColumn();// 内側に線を引くセルが無いif (colF >= colT) {return;}for (int col = colF; col < colT; col++) {// CellRangeAddress wRng = new CellRangeAddress( rowF, rowT, col,// col );// HSSFRegionUtil.setBorderRight(borderStyle, wRng,// hssfSheet,hssfBook);for (int row = rowF; row <= rowT; row++) {xlCell = getCell(row, col);// スタイル設定前の情報を保持styleCurr = xlCell.getCellStyle();// 前セルと今回セルで同じスタイルなら次if (styleCurr.equals(stylePrev)) {// 前回作成したスタイルをそのまま使用xlCell.setCellStyle(style);continue;}// 前セルの設定stylePrev = xlCell.getCellStyle();// 現在設定されているスタイルに今回スタイル設定を加えるstyle = hssfBook.createCellStyle(); // 新スタイル作成style.cloneStyleFrom(xlCell.getCellStyle()); // 設定済スタイルのコピー// 線の色の設定style.setRightBorderColor(color);// 線の設定style.setBorderRight(borderStyle);// スタイル適用xlCell.setCellStyle(style);}}}// public void init(int rowF,int rowT,int colF,int colT) {// HSSFCellStyle style = null;// HSSFCell xlCell;//// style = xlBook.createCellStyle();//// for (int col=colF;col<=colT;col++) {// for (int row=rowF;row<=rowT;row++) {//// xlCell = getCell(row, col);// xlCell.setCellStyle(style);// }// }// }/*** 1シート内の最大明細分を描画する** @param xlSheet*            EXCELのシート* @param startRow*            開始行* @param maxRow*            最大行* @param maxCol*            最大列* @param listSize*            データ件数*/public static void addEmptyRows(ExcelSheet xlSheet, int startRow, int maxRow, int maxCol, int listSize) {int emptyRows = maxRow;if (listSize - maxRow > 0) {int i = listSize - maxRow;while (i > 0) {emptyRows = emptyRows + maxRow;i = i - maxRow;}}for (int i = startRow + listSize; i < startRow + emptyRows; i++) {for (int j = 1; j <= maxCol; j++) {xlSheet.setCellVal(i, j, "");}setCellStyle(xlSheet, startRow, maxCol, i);}}/*** セルにフォーマットを設定する処理** @param xlSheet*            EXCELのシート* @param startRow*            開始行* @param maxCol*            最大列* @param intRow*            行数*/public static void setCellStyle(ExcelSheet xlSheet, int startRow, int maxCol, int intRow) {if (intRow == startRow) {return;}short shortRowHeight = xlSheet.getRow(startRow).getHeight();xlSheet.getRow(intRow).setHeight(shortRowHeight);for (int i = 0; i < maxCol; i++) {CellStyle cellStyle = xlSheet.getRow(startRow).getCell(i).getCellStyle();xlSheet.getRow(intRow).getCell(i).setCellStyle(cellStyle);}}/*** 1シート内の最大明細分を描画する(複数行指定)** @param xlSheet*            EXCELのシート* @param startRow*            開始行* @param rowCnt*            雛型行数* @param maxRow*            最大行* @param maxCol*            最大列* @param listSize*            データ件数*/public static void addEmptyRowns(ExcelSheet xlSheet, int startRow, int rowCnt, int maxRow, int maxCol, int listSize) {int emptyRows = maxRow;if (listSize - maxRow > 0) {int i = listSize - maxRow;while (i > 0) {emptyRows = emptyRows + maxRow;i = i - maxRow;}}for (int i = startRow + listSize; i < startRow + emptyRows; i++) {for (int j = 1; j <= maxCol; j++) {xlSheet.setCellVal(i, j, "");}if ((i - startRow + 1) % rowCnt == 0) {setCellStyles(xlSheet, startRow, rowCnt, maxCol, i);}}}/*** セルにフォーマットを設定する処理(複数行指定)** @param xlSheet*            EXCELのシート* @param startRow*            開始行* @param rowCnt*            雛型行数* @param maxCol*            最大列* @param intRow*            行数*/public static void setCellStyles(ExcelSheet xlSheet, int startRow, int rowCnt, int maxCol, int intRow) {int row = intRow - rowCnt + 1;if (row == startRow) {return;}for (int i = 0; i < rowCnt; i++) {for (int j = 0; j < maxCol; j++) {CellStyle cellStyle = xlSheet.getRow(startRow + i).getCell(j).getCellStyle();xlSheet.getRow(row + i).getCell(j).setCellStyle(cellStyle);}short shortRowHeight = xlSheet.getRow(startRow + i).getHeight();xlSheet.getRow(row + i).setHeight(shortRowHeight);}}/*** SXSSFWorkbookを作成する** @param outFileFullPath* @return* @throws FileNotFoundException* @throws IOException*/public static Workbook createSXSSFWorkbook(String outFileFullPath) throws FileNotFoundException, IOException {Workbook workBook;FileInputStream in = null;try {in = new FileInputStream(outFileFullPath);workBook = new XSSFWorkbook(in);workBook = new SXSSFWorkbook((XSSFWorkbook) workBook);} finally {IOUtils.closeQuietly(in);}return workBook;}/*** 書式の作成** @param workBook* @param border* @param color* @return*/public static CellStyle createCellStyle(Workbook workBook, short border, short color, short dataFormat) {CellStyle style = createCellStyleBorder(workBook, border, border, border, border, color, dataFormat,CellStyle.ALIGN_GENERAL);return style;}/*** 書式の作成** @param workBook* @param border* @param color* @return*/public static CellStyle createCellStyleBorder(Workbook workBook, short borderTop, short borderBotom,short borderLeft, short borderRight, short color, short dataFormat, short align) {// 現在設定されているスタイルに今回スタイル設定を加えるCellStyle style = workBook.createCellStyle(); // 新スタイル作成// セルの上部の罫線を設定するstyle.setBorderTop(borderTop);// セルの上部の罫線の色を設定するstyle.setTopBorderColor(color);// セルの下部の罫線を設定するstyle.setBorderBottom(borderBotom);// セルの下部の罫線の色を設定するstyle.setBottomBorderColor(color);// セルの左側の罫線を設定するstyle.setBorderLeft(borderLeft);// セルの左側の罫線の色を設定するstyle.setLeftBorderColor(color);// セルの右側の罫線を設定するstyle.setBorderRight(borderRight);// セルの右側の罫線の色を設定するstyle.setRightBorderColor(color);// セルの水平方向の位置style.setAlignment(align);if (dataFormat != 0) {// 書式を設定style.setDataFormat(dataFormat);}return style;}/*** Excelを作成する** @param outFileFullPath* @param workBook*/public static void saveExcel(String outFileFullPath, Workbook workBook) {try {FileOutputStream fos = new FileOutputStream(outFileFullPath);workBook.write(fos);fos.flush();fos.close();if (workBook != null) {try {/** SXSSFWorkbookはメモリ空間を節約する代わりにテンポラリファイルを大量に生成するため、* 不要になった段階でdisposeしてテンポラリファイルを削除する必要がある*/((SXSSFWorkbook) workBook).dispose();} catch (Exception e) {}}} catch (IOException e) {e.printStackTrace();}}// *********************************************************************************************/*** 指定セルへ値を設定** @param row* @param col* @return*/// *********************************************************************************************public static void setCellVal(Sheet xlSheet, int row, int col, Object val) {try {Cell xlCell;xlCell = getCell(xlSheet, row, col);if (val == null) {xlCell.setCellValue("");} else if (val instanceof Integer) {xlCell.setCellValue((Integer) val);} else if (val instanceof Long) {xlCell.setCellValue((Long) val);} else if (val instanceof Date) {xlCell.setCellValue((Date) val);} else if (val instanceof Double) {xlCell.setCellValue((Double) val);} else if (val instanceof BigDecimal) {BigDecimal b = new BigDecimal(val.toString());xlCell.setCellValue((Double) b.doubleValue());} else if (val instanceof Float) {xlCell.setCellValue((Float) val);} else if (val instanceof Boolean) {xlCell.setCellValue((Boolean) val);} else if (val instanceof Calendar) {xlCell.setCellValue((Calendar) val);} else {xlCell.setCellValue(val.toString());}// エラーがあっても処理を継続} catch (Exception ex) {;}}// *********************************************************************************************/*** 指定セルへ値を設定** @param row* @param col* @return*/// *********************************************************************************************public static void setCellValStyle(Sheet xlSheet, int row, int col, Object val, CellStyle style) {try {Cell xlCell;xlCell = getCell(xlSheet, row, col);if (val == null) {xlCell.setCellValue("");} else if (val instanceof Integer) {xlCell.setCellValue((Integer) val);} else if (val instanceof Long) {xlCell.setCellValue((Long) val);} else if (val instanceof Date) {xlCell.setCellValue((Date) val);} else if (val instanceof Double) {xlCell.setCellValue((Double) val);} else if (val instanceof BigDecimal) {BigDecimal b = new BigDecimal(val.toString());xlCell.setCellValue((Double) b.doubleValue());} else if (val instanceof Float) {xlCell.setCellValue((Float) val);} else if (val instanceof Boolean) {xlCell.setCellValue((Boolean) val);} else if (val instanceof Calendar) {xlCell.setCellValue((Calendar) val);} else {xlCell.setCellValue(val.toString());}xlCell.setCellStyle(style);// エラーがあっても処理を継続} catch (Exception ex) {;}}// ---------------------------------------------------------------------------------------------//// セル//// ---------------------------------------------------------------------------------------------// *********************************************************************************************/*** 指定したセルの取得** @param row*            行の指定* @param col*            列の指定* @return セル*/// *********************************************************************************************public static Cell getCell(Sheet xlSheet, int row, int col) {Row xlRow;Cell xlCell;// 行の取得xlRow = getRow(xlSheet, row);// セルの取得xlCell = xlRow.getCell(col - 1);if (xlCell == null) {// セルオブジェクトの作成xlCell = xlRow.createCell(col - 1);}return xlCell;}// *********************************************************************************************/*** 指定した行の取得** @param row*            行の指定* @return 行*/// *********************************************************************************************public static Row getRow(Sheet xlSheet, int row) {Row xlRow = xlSheet.getRow(row - 1);if (xlRow == null) {// 行オブジェクトの作成xlRow = xlSheet.createRow(row - 1);}return xlRow;}// *********************************************************************************************/*** 指定列を隠す(単列)*/// *********************************************************************************************public static void setColumnHidden(Sheet xlSheet, boolean bol, int col) {xlSheet.setColumnHidden(col - 1, bol);}// *********************************************************************************************/*** 指定列を隠す(複数列)*/// *********************************************************************************************public static void setColumnHidden(Sheet xlSheet, boolean bol, int colF, int colT) {for (int col = colF; col <= colT; col++) {xlSheet.setColumnHidden(col - 1, bol);}}/*** 指定のシートを hidden 状態にする** @param bol* @param sheetNm*/public static void setSheetHidden(Workbook wrkBook, boolean bol, String sheetNm) {try {Integer sheetIndex = wrkBook.getSheetIndex(sheetNm);Integer firstVisibleIndex = wrkBook.getFirstVisibleTab();wrkBook.setSheetHidden(sheetIndex, bol);// 先頭シートを非表示にした場合// (Excel左下のシート先頭へ移動ボタンを押下するとExcelが異常終了する対応)if (sheetIndex == firstVisibleIndex) {wrkBook.setFirstVisibleTab(sheetIndex + 1);}} catch (Exception ex) {// エラーは無視}}// *********************************************************************************************/*** 指定した範囲のセルの結合** @param rowF*            firstRow (行)* @param rowT*            lastRow (行)* @param colF*            firstCol (列)* @param colT*            lastCol (列)*/// *********************************************************************************************public static void mergeCell(Sheet xlSheet, int rowF, int rowT, int colF, int colT) {xlSheet.addMergedRegion(new CellRangeAddress(rowF - 1, rowT - 1, colF - 1, colT - 1));}// *********************************************************************************************/*** 指定範囲内のセルにスタイルを設定** @param rowF*            開始位置(行)* @param rowT*            終了位置(行)* @param colF*            開始位置(列)* @param colT*            終了位置(列)* @param color*            色*/// *********************************************************************************************public static void setRngStyle(Sheet xlSheet, int rowF, int rowT, int colF, int colT, CellStyle style) {Cell xlCell = null;for (int col = colF; col <= colT; col++) {for (int row = rowF; row <= rowT; row++) {xlCell = getCell(xlSheet, row, col);xlCell.setCellStyle(style);}}}// *********************************************************************************************/*** 複数セルに対してまとめて罫線を引く(Bottom)** @param borderStyle*            罫線のスタイル* @param rng*            範囲*/// *********************************************************************************************public static void setRngBorderBottom(Workbook workBook, Sheet xlSheet, CellRangeAddress inRng, short borderStyle,short color) {CellStyle stylePrev = null; // 前回セルのスタイル(今回の色設定前)CellStyle styleCurr = null; // 現在セルのスタイル(今回の色設定前)CellStyle style = null;Cell xlCell = null;int rowT = inRng.getLastRow();int colF = inRng.getFirstColumn();int colT = inRng.getLastColumn();// 指定の範囲で罫線を設定するfor (int col = colF; col <= colT; col++) {xlCell = getCell(xlSheet, rowT, col);// スタイル設定前の情報を保持styleCurr = xlCell.getCellStyle();// 前セルと今回セルで同じスタイルなら次if (styleCurr.equals(stylePrev)) {// 前回作成したスタイルをそのまま使用xlCell.setCellStyle(style);continue;}// 前セルの設定stylePrev = xlCell.getCellStyle();// 現在設定されているスタイルに今回スタイル設定を加えるstyle = workBook.createCellStyle(); // 新スタイル作成style.cloneStyleFrom(xlCell.getCellStyle()); // 設定済スタイルのコピー// 線の色の設定style.setBottomBorderColor(color);// 線の設定style.setBorderBottom(borderStyle);// スタイル適用xlCell.setCellStyle(style);}}}

java 使用poi生成excel相关推荐

  1. java使用poi生成Excel文件并合并单元格

    java使用poi生成Excel文件并合并单元格        业务需要根据 分管部门 字段进行合并,现在提供一种思路. controller层 @Inject(target = "/inf ...

  2. java通过poi生成excel表格(自适应列宽、合并单元格后的边框添加)

    具体java通过POI读写Excel的基本使用方法可参考: POI读写Excel的基本使用 1.项目导入依赖: <!--xls--> <dependency><group ...

  3. java用poi 生成excel并单元格,字体,样式

    1.最近根据客户需求,需要生成要求的excell 格式 索性研究了下用POI 生成这个excel的功能,poi可以合并单元格(合并列,全并行)及字体,边框等,能满足大部分格式样式,写了个简单的测试列子 ...

  4. Java利用POI生成Excel强制换行

    前一段时间在做一个学校排课系统时,有一个地方需要利用把课程表生成excel汇出给客户,由于之前用excel都只是简单的应用,在单元格里都是用自动换行,而这次可能需要用到手动强制换行.  于是我在网上找 ...

  5. java通过poi生成excel并下载出现文件打不开、文件格式和文件扩展名无效问题的分析与解决

    需求描述: 需要完成这样一个功能:后台通过poi生成excle,前台点击按钮可直接下载. 代码逻辑(核心部分): 第一种: public String generatePlanExcel(@Reque ...

  6. java利用poi生成excel如何自动换行

    1.首先设置单元格内容自动换行 // 生成一个样式,用于设置内容样式 HSSFWorkbook workbook = new HSSFWorkbook(); HSSFCellStyle cellSty ...

  7. java导出excel设置行高列宽_使用POI生成Excel文件,可以自动调整excel列宽

    //autoSizeColumn()方法自动调整excel列宽 importjava.io.FileOutputStream; importorg.apache.poi.hssf.usermodel. ...

  8. java后台处理excel_java后台利用Apache poi 生成excel文档提供前台下载示例

    之前在项目中会用到在java在后台把数据填入Word文档的模板来提供前台下载,为了自己能随时查看当时的实现方案及方便他人学习我写了这篇博客,访问量已经是我写的博客里第一了.于是乎我在学会用Java在后 ...

  9. Java 调用Poi 生成费用报销单Excel

    整个代码有点多,并没有做优化.目前只是为了功能实现.可以直接复制,创建main方法运行 默认一张A4纸,可以存放2个报销单模板. 如果只想一张A4纸,存放一个报销单.可以从分割线以下代码删除掉.其对应 ...

最新文章

  1. python中md5_Python的md5是什么意思
  2. 思科ucs-b系列服务器,思科统一计算系统UCS B系列刀片推荐
  3. 中标麒麟桌面版yum安装mysql_中标麒麟Neokylin6桌面版如何本地yum安装软件
  4. 在c语言中错误的常数表示是,C语言程序设计试题
  5. 冒泡排序python实现
  6. 神经信息学整理(2)-caianiello神经方程(1)
  7. Springboot项目中配置tomcta监控日志
  8. The Everyman's Guide to How Network Packets Are Routed Across the Web
  9. Android使用的设计模式2——策略模式
  10. Android学习系列(34)--App应用之发布各广告平台版本
  11. android电视机清理内存,电视盒子总是内存不足?五大清理方法释放更多内存
  12. PHP 实现身份证号实名认证功能
  13. 记忆力训练软件测试自学,[记忆力训练软件]记忆力训练软件有哪些?
  14. java计算机毕业设计小型企业员工工资管理系统源码+系统+数据库+lw文档+mybatis+运行部署
  15. Android签名证书的生成
  16. 浏览量比较大的网站应该从哪几个方面入手
  17. 关于AttributeError: module ‘torch.nn‘ has no attribute ‘Moudle‘的解决方法
  18. KVM详细介绍及搭建KVM虚拟化平台构建Centos7系统
  19. 利用python进行AdaBoost模型预测
  20. Android小游戏开发:简单的合金弹头游戏(一)游戏框架

热门文章

  1. springmvc返回不带引号的字符串
  2. 浏览器 unload beforunload事件不触发
  3. ArcGIS基础实验操作100例--实验84查找面到直线的最近点位置
  4. AAC音频文件添加ADTS头
  5. 【树莓派C语言开发】实验12:PCF8591模数转换器模块
  6. uni-app 学习笔记 黑马优购商城
  7. stm32f103系列开发板控制对数码管来显示自定义时间(自主学习)
  8. Protobuf自动反射消息类型的网络传输方案
  9. 安装wxpython for Python3.5
  10. 无人驾驶汽车发展史大事纪实