提交 b67e9f17 编写于 作者: R roo00

删除说明类

上级 96da0e27

要显示的变更太多。

To preserve performance only 1000 of 1000+ files are displayed.
package com.x.attendance.assemble.common.excel.reader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.eventusermodel.EventWorkbookBuilder.SheetRecordCollectingListener;
import org.apache.poi.hssf.eventusermodel.FormatTrackingHSSFListener;
import org.apache.poi.hssf.eventusermodel.HSSFEventFactory;
import org.apache.poi.hssf.eventusermodel.HSSFListener;
import org.apache.poi.hssf.eventusermodel.HSSFRequest;
import org.apache.poi.hssf.eventusermodel.MissingRecordAwareHSSFListener;
import org.apache.poi.hssf.eventusermodel.dummyrecord.LastCellOfRowDummyRecord;
import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingCellDummyRecord;
import org.apache.poi.hssf.model.HSSFFormulaParser;
import org.apache.poi.hssf.record.BOFRecord;
import org.apache.poi.hssf.record.BlankRecord;
import org.apache.poi.hssf.record.BoolErrRecord;
import org.apache.poi.hssf.record.BoundSheetRecord;
import org.apache.poi.hssf.record.FormulaRecord;
import org.apache.poi.hssf.record.LabelRecord;
import org.apache.poi.hssf.record.LabelSSTRecord;
import org.apache.poi.hssf.record.NumberRecord;
import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.SSTRecord;
import org.apache.poi.hssf.record.StringRecord;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
/**
* 抽象Excel2003读取器,通过实现HSSFListener监听器,采用事件驱动模式解析excel2003
* 中的内容,遇到特定事件才会触发,大大减少了内存的使用。
*
*/
public class Excel2003Reader implements HSSFListener{
private int minColumns = -1;
private POIFSFileSystem fs;
private int lastRowNumber;
private int lastColumnNumber;
/** Should we output the formula, or the value it has? */
private boolean outputFormulaValues = true;
/** For parsing Formulas */
private SheetRecordCollectingListener workbookBuildingListener;
//excel2003工作薄
private HSSFWorkbook stubWorkbook;
// Records we pick up as we process
private SSTRecord sstRecord;
private FormatTrackingHSSFListener formatListener;
//表索引
private int sheetIndex = -1;
private BoundSheetRecord[] orderedBSRs;
@SuppressWarnings("rawtypes")
private ArrayList boundSheetRecords = new ArrayList();
// For handling formulas with string results
private int nextRow;
private int nextColumn;
private boolean outputNextStringRecord;
//当前行
private int curRow = 0;
//存储行记录的容器
private List<String> rowlist = new ArrayList<String>();;
@SuppressWarnings( "unused")
private String sheetName;
private String fileKey;
private int startRow;
private IRowReader rowReader;
public void setRowReader(IRowReader rowReader, String fileKey, int startRow ){
this.rowReader = rowReader;
this.fileKey = fileKey;
this.startRow = startRow;
}
/**
* 遍历excel下所有的sheet
* @param fileKey
* @throws IOException
*/
public void process(String fileName ) throws IOException {
this.fs = new POIFSFileSystem(new FileInputStream(fileName));
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener( this);
formatListener = new FormatTrackingHSSFListener(listener);
HSSFEventFactory factory = new HSSFEventFactory();
HSSFRequest request = new HSSFRequest();
if ( outputFormulaValues ) {
request.addListenerForAllRecords( formatListener );
} else {
workbookBuildingListener = new SheetRecordCollectingListener( formatListener);
request.addListenerForAllRecords(workbookBuildingListener);
}
factory.processWorkbookEvents(request, fs);
//数据读取完成
}
/**
* 遍历excel下所有的sheet
* @param fileKey
* @throws IOException
*/
public void process( InputStream is ) throws IOException {
this.fs = new POIFSFileSystem( is );
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener( this);
formatListener = new FormatTrackingHSSFListener(listener);
HSSFEventFactory factory = new HSSFEventFactory();
HSSFRequest request = new HSSFRequest();
if ( outputFormulaValues ) {
request.addListenerForAllRecords( formatListener );
} else {
workbookBuildingListener = new SheetRecordCollectingListener( formatListener);
request.addListenerForAllRecords(workbookBuildingListener);
}
factory.processWorkbookEvents(request, fs);
//数据读取完成
}
/**
* HSSFListener 监听方法,处理 Record
*/
@SuppressWarnings("unchecked")
public void processRecord(Record record) {
int thisRow = -1;
int thisColumn = -1;
String thisStr = null;
String value = null;
switch (record.getSid()) {
case BoundSheetRecord.sid:
boundSheetRecords.add(record);
break;
case BOFRecord.sid:
BOFRecord br = (BOFRecord) record;
if (br.getType() == BOFRecord.TYPE_WORKSHEET) {
// 如果有需要,则建立子工作薄
if (workbookBuildingListener != null && stubWorkbook == null) {
stubWorkbook = workbookBuildingListener
.getStubHSSFWorkbook();
}
sheetIndex++;
if (orderedBSRs == null) {
orderedBSRs = BoundSheetRecord
.orderByBofPosition(boundSheetRecords);
}
sheetName = orderedBSRs[sheetIndex].getSheetname();
}
break;
case SSTRecord.sid:
sstRecord = (SSTRecord) record;
break;
case BlankRecord.sid:
BlankRecord brec = (BlankRecord) record;
thisRow = brec.getRow();
thisColumn = brec.getColumn();
thisStr = "";
rowlist.add(thisColumn, thisStr);
break;
case BoolErrRecord.sid: //单元格为布尔类型
BoolErrRecord berec = (BoolErrRecord) record;
thisRow = berec.getRow();
thisColumn = berec.getColumn();
thisStr = berec.getBooleanValue()+"";
rowlist.add(thisColumn, thisStr);
break;
case FormulaRecord.sid: //单元格为公式类型
FormulaRecord frec = (FormulaRecord) record;
thisRow = frec.getRow();
thisColumn = frec.getColumn();
if (outputFormulaValues) {
if (Double.isNaN(frec.getValue())) {
// Formula result is a string
// This is stored in the next record
outputNextStringRecord = true;
nextRow = frec.getRow();
nextColumn = frec.getColumn();
} else {
thisStr = formatListener.formatNumberDateCell(frec);
}
} else {
thisStr = '"' + HSSFFormulaParser.toFormulaString(stubWorkbook, frec.getParsedExpression()) + '"';
}
rowlist.add(thisColumn,thisStr);
break;
case StringRecord.sid://单元格中公式的字符串
if (outputNextStringRecord) {
// String for formula
StringRecord srec = (StringRecord) record;
thisStr = srec.getString();
thisRow = nextRow;
thisColumn = nextColumn;
outputNextStringRecord = false;
}
break;
case LabelRecord.sid:
LabelRecord lrec = (LabelRecord) record;
curRow = thisRow = lrec.getRow();
thisColumn = lrec.getColumn();
value = lrec.getValue().trim();
value = value.equals("")?" ":value;
this.rowlist.add(thisColumn, value);
break;
case LabelSSTRecord.sid: //单元格为字符串类型
LabelSSTRecord lsrec = (LabelSSTRecord) record;
curRow = thisRow = lsrec.getRow();
thisColumn = lsrec.getColumn();
if (sstRecord == null) {
rowlist.add(thisColumn, " ");
} else {
value = sstRecord
.getString(lsrec.getSSTIndex()).toString().trim();
value = value.equals("")?" ":value;
rowlist.add(thisColumn,value);
}
break;
case NumberRecord.sid: //单元格为数字类型
NumberRecord numrec = (NumberRecord) record;
curRow = thisRow = numrec.getRow();
thisColumn = numrec.getColumn();
value = formatListener.formatNumberDateCell(numrec).trim();
value = value.equals("")?" ":value;
// 向容器加入列值
rowlist.add(thisColumn, value);
break;
default:
break;
}
// 遇到新行的操作
if (thisRow != -1 && thisRow != lastRowNumber) {
lastColumnNumber = -1;
}
// 空值的操作
if (record instanceof MissingCellDummyRecord) {
MissingCellDummyRecord mc = (MissingCellDummyRecord) record;
curRow = thisRow = mc.getRow();
thisColumn = mc.getColumn();
rowlist.add(thisColumn," ");
}
// 更新行和列的值
if (thisRow > -1)
lastRowNumber = thisRow;
if (thisColumn > -1)
lastColumnNumber = thisColumn;
// 行结束时的操作
if (record instanceof LastCellOfRowDummyRecord) {
if (minColumns > 0) {
// 列值重新置空
if (lastColumnNumber == -1) {
lastColumnNumber = 0;
}
}
lastColumnNumber = -1;
// 每行结束时, 调用getRows() 方法
rowReader.getRows(sheetIndex,curRow, rowlist, this.fileKey, this.startRow );
// 清空容器
rowlist.clear();
}
}
}
package com.x.attendance.assemble.common.excel.reader;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
/**
* 抽象Excel2007读取器,excel2007的底层数据结构是xml文件,采用SAX的事件驱动的方法解析
* xml,需要继承DefaultHandler,在遇到文件内容时,事件会触发,这种做法可以大大降低
* 内存的耗费,特别使用于大数据量的文件。
*
*/
public class Excel2007Reader extends DefaultHandler {
//共享字符串表
private SharedStringsTable sst;
//上一次的内容
private String lastContents;
private boolean nextIsString;
private int sheetIndex = -1;
private List<String> rowlist = new ArrayList<String>();
//当前行
private int curRow = 0;
//当前列
private int curCol = 0;
//日期标志
private boolean dateFlag;
//数字标志
private boolean numberFlag;
private boolean isTElement;
private String fileKey;
private int startRow;
private IRowReader rowReader;
public void setRowReader( IRowReader rowReader, String fileKey, int startRow ){
this.rowReader = rowReader;
this.fileKey = fileKey;
this.startRow = startRow;
}
/**只遍历一个电子表格,其中sheetId为要遍历的sheet索引,从1开始,1-3
* @param filename
* @param sheetId
* @throws Exception
*/
public void processOneSheet(String filename,int sheetId) throws Exception {
OPCPackage pkg = OPCPackage.open(filename);
XSSFReader r = new XSSFReader(pkg);
SharedStringsTable sst = r.getSharedStringsTable();
XMLReader parser = fetchSheetParser(sst);
// 根据 rId# 或 rSheet# 查找sheet
InputStream sheet2 = r.getSheet("rId"+sheetId);
sheetIndex++;
InputSource sheetSource = new InputSource(sheet2);
parser.parse(sheetSource);
sheet2.close();
}
/**
* 遍历工作簿中所有的电子表格
* @param filename
* @param fileKey
* @throws Exception
*/
public void process( String filename ) throws Exception {
OPCPackage pkg = OPCPackage.open(filename);
XSSFReader r = new XSSFReader(pkg);
SharedStringsTable sst = r.getSharedStringsTable();
XMLReader parser = fetchSheetParser(sst);
Iterator<InputStream> sheets = r.getSheetsData();
while (sheets.hasNext()) {
curRow = 0;
sheetIndex++;
InputStream sheet = sheets.next();
InputSource sheetSource = new InputSource(sheet);
parser.parse( sheetSource );
sheet.close();
}
//数据读取完成
}
/**
* 遍历工作簿中所有的电子表格
* @param filename
* @param fileKey
* @throws Exception
*/
public void process( InputStream is ) throws Exception {
OPCPackage pkg = OPCPackage.open( is );
XSSFReader r = new XSSFReader(pkg);
SharedStringsTable sst = r.getSharedStringsTable();
XMLReader parser = fetchSheetParser(sst);
Iterator<InputStream> sheets = r.getSheetsData();
while (sheets.hasNext()) {
curRow = 0;
sheetIndex++;
InputStream sheet = sheets.next();
InputSource sheetSource = new InputSource(sheet);
parser.parse( sheetSource );
sheet.close();
}
}
public XMLReader fetchSheetParser(SharedStringsTable sst) throws SAXException {
XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
this.sst = sst;
parser.setContentHandler(this);
return parser;
}
public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
// c => 单元格
if ("c".equals(name)) {
// 如果下一个元素是 SST 的索引,则将nextIsString标记为true
String cellType = attributes.getValue("t");
if ("s".equals(cellType)) {
nextIsString = true;
} else {
nextIsString = false;
}
//日期格式
String cellDateType = attributes.getValue("s");
if ("1".equals(cellDateType)){
dateFlag = true;
} else {
dateFlag = false;
}
String cellNumberType = attributes.getValue("s");
if("2".equals(cellNumberType)){
numberFlag = true;
} else {
numberFlag = false;
}
}
//当元素为t时
if("t".equals(name)){
isTElement = true;
} else {
isTElement = false;
}
// 置空
lastContents = "";
}
public void endElement(String uri, String localName, String name)
throws SAXException {
// 根据SST的索引值的到单元格的真正要存储的字符串
// 这时characters()方法可能会被调用多次
if (nextIsString) {
try {
int idx = Integer.parseInt(lastContents);
lastContents = new XSSFRichTextString(sst.getEntryAt(idx))
.toString();
} catch (Exception e) {
}
}
//t元素也包含字符串
if(isTElement){
String value = lastContents.trim();
rowlist.add(curCol, value);
curCol++;
isTElement = false;
// v => 单元格的值,如果单元格是字符串则v标签的值为该字符串在SST中的索引
// 将单元格内容加入rowlist中,在这之前先去掉字符串前后的空白符
} else if ("v".equals(name)) {
String value = lastContents.trim();
value = value.equals("")?" ":value;
//日期格式处理
if(dateFlag){
try{
Date date = HSSFDateUtil.getJavaDate(Double.valueOf(value));
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
value = dateFormat.format(date);
}catch(Exception e){
}
}
//数字类型处理
if(numberFlag){
try{
BigDecimal bd = new BigDecimal(value);
value = bd.setScale(3,BigDecimal.ROUND_UP).toString();
}catch(Exception e){
}
}
rowlist.add(curCol, value);
curCol++;
}else {
//如果标签名称为 row ,这说明已到行尾,调用 optRows() 方法
if (name.equals("row")) {
rowReader.getRows(sheetIndex,curRow,rowlist, this.fileKey, this.startRow );
rowlist.clear();
curRow++;
curCol = 0;
}
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
//得到单元格内容的值
lastContents += new String(ch, start, length);
}
}
package com.x.attendance.assemble.common.excel.reader;
import java.io.InputStream;
public class ExcelReaderUtil {
//excel2003扩展名
public static final String EXCEL03_EXTENSION = ".xls";
//excel2007扩展名
public static final String EXCEL07_EXTENSION = ".xlsx";
/**
* 读取Excel文件,可能是03也可能是07版本
* @param excel03
* @param excel07
* @param fileName
* @throws Exception
*/
public static void readExcel( IRowReader reader, String fileName, String fileKey, int startRow ) throws Exception{
// 处理excel2003文件
if (fileName.endsWith(EXCEL03_EXTENSION)){
Excel2003Reader excel03 = new Excel2003Reader();
excel03.setRowReader(reader, fileKey, startRow);
excel03.process(fileName);
// 处理excel2007文件
} else if (fileName.endsWith(EXCEL07_EXTENSION)){
Excel2007Reader excel07 = new Excel2007Reader();
excel07.setRowReader(reader, fileKey, startRow);
excel07.process(fileName);
} else {
throw new Exception("文件格式错误,fileName的扩展名只能是xls或xlsx。");
}
}
public static void readExcel( IRowReader reader, InputStream is, String fileName, String fileKey, int startRow ) throws Exception{
// 处理excel2003文件
if (fileName.endsWith(EXCEL03_EXTENSION)){
if ( is != null ){
Excel2003Reader excel03 = new Excel2003Reader();
excel03.setRowReader( reader, fileKey, startRow );
excel03.process( is );
} else {
throw new Exception("there is no input stream.");
}
// 处理excel2007文件
} else if (fileName.endsWith(EXCEL07_EXTENSION)){
if ( is != null ){
Excel2007Reader excel07 = new Excel2007Reader();
excel07.setRowReader(reader, fileKey, startRow);
excel07.process( is );
} else {
throw new Exception("there is no input stream.");
}
} else {
throw new Exception("文件格式错误,fileName的扩展名只能是xls或xlsx。");
}
}
}
\ No newline at end of file
package com.x.attendance.assemble.common.excel.reader;
import java.util.List;
public interface IRowReader {
/**业务逻辑实现方法
* @param sheetIndex
* @param curRow
* @param rowlist
*/
public void getRows(int sheetIndex,int curRow, List<String> rowlist, String fileKey, int startRow);
}
package com.x.attendance.assemble.common.excel.reader;
import java.util.List;
import com.x.attendance.assemble.control.processor.sender.SenderForValidateData;
public class ImportExcelReader implements IRowReader{
/* 业务逻辑实现方法
* @see com.eprosun.util.excel.IRowReader#getRows(int, int, java.util.List)
*/
public void getRows( int sheetIndex, int curRow, List<String> colmlist, String fileKey, int startRow ) {
if( curRow < startRow ){
return;
}
if( colmlist != null && !colmlist.isEmpty() ) {
if( !colmlist.get(0).isEmpty() && !colmlist.get(2).isEmpty()){
new SenderForValidateData().execute( sheetIndex, curRow, colmlist, fileKey );
}
}
}
}
package com.x.attendance.assemble.common.excel.reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.hssf.eventusermodel.EventWorkbookBuilder.SheetRecordCollectingListener;
import org.apache.poi.hssf.eventusermodel.HSSFListener;
import org.apache.poi.hssf.record.BOFRecord;
import org.apache.poi.hssf.record.BlankRecord;
import org.apache.poi.hssf.record.BoolErrRecord;
import org.apache.poi.hssf.record.BoundSheetRecord;
import org.apache.poi.hssf.record.FormulaRecord;
import org.apache.poi.hssf.record.LabelSSTRecord;
import org.apache.poi.hssf.record.NumberRecord;
import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.RowRecord;
import org.apache.poi.hssf.record.SSTRecord;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
/**
* 基于POI HSSF的eventmodel 模型的时间解析方式
* 优点:解析数据相当快。
* 缺点:1.仅仅支持97~2003版本的excel,不支持2007版本的excel。
* 2.只能读Excel中一个Sheet页面。
*
* @Title:
* @Description: 实现TODO
* @Copyright:Copyright (c) 2011
* @Date:2012-6-14
* @author O2LEE
* @version 1.0
*/
public class UserModelEventListener implements HSSFListener {
private static Logger logger=LoggerFactory.getLogger( UserModelEventListener.class );
private SSTRecord sstrec;
/** Should we output the formula, or the value it has? */
private boolean outputFormulaValues = true;
/** For parsing Formulas */
private SheetRecordCollectingListener workbookBuildingListener;
//当前Sheet的内容
private List<Map<String,Object>> currentSheetDataMap=new ArrayList<Map<String,Object>>();
//列对应的字段
private static String[] trianListheadTitle=new String[]{"trainCode","firstStation","lastStation","startStation","arriveStation","startTime","arriveTime","fistLevelPrice","secondLevelPrice","km","useDate"};
//一行记录
private Map<String,Object> currentSheetRowDataMap=new HashMap<String,Object>();
private int curRowNum=0;
private int ignoreRowNum=1;
private int sheetNo=0;
private Boolean debugger = false;
@Override
public void processRecord( Record record ) {
switch (record.getSid()) {
case BOFRecord.sid:
BOFRecord bof = (BOFRecord) record;
//顺序进入新的Workbook
if (bof.getType() == bof.TYPE_WORKBOOK) {
logger.debug( debugger, ">>>>>>>>>>开始解析excel 文档.....");
//顺序进入新的Worksheet,因为Event API不会把Excel文件里的所有数据结构都关联起来,
//所以这儿一定要记录现在进入第几个sheet了。
} else if (bof.getType() == bof.TYPE_WORKSHEET) {
//读取新的一个Sheet页
logger.debug( debugger, ">>>>>>>>>>开始解析sheet页面内容...");
sheetNo++;
currentSheetDataMap=new ArrayList<Map<String,Object>>();
}
break;
//开始解析Sheet的信息,记录sheet,这儿会把所有的sheet都顺序打印出来,如果有多个sheet的话,可以顺序记入到一个List里
case BoundSheetRecord.sid:
BoundSheetRecord bsr = (BoundSheetRecord) record;
logger.debug( debugger, ">>>>>>>>>>New sheet named: " + bsr.getSheetname());
break;
//执行行记录事件
case RowRecord.sid:
RowRecord rowrec = (RowRecord) record;
logger.debug( debugger, ">>>>>>>>>>记录开始, first column at "
+ rowrec.getFirstCol() + " last column at "
+ rowrec.getLastCol());
break;
// SSTRecords store a array of unique strings used in Excel.
case SSTRecord.sid:
sstrec = (SSTRecord) record;
for (int k = 0; k < sstrec.getNumUniqueStrings(); k++) {
logger.debug( debugger, ">>>>>>>>>>String table value " + k + " = "
+ sstrec.getString(k));
}
break;
//发现数字类型的cell,因为数字和日期都是用这个格式,所以下面一定要判断是不是日期格式,另外默认的数字也会被视为日期格式,所以如果是数字的话,一定要明确指定格式!!!!!!!
case NumberRecord.sid:
NumberRecord nr = (NumberRecord) record;
//HSSFDateUtil.isInternalDateFormat(nr.getXFIndex()) 判断是否为时间列
int column=nr.getColumn();
if(column==5||column==6){
addDataAndrChangeRow(nr.getRow(),nr.getColumn(),getTime(nr.getValue()), debugger);
}else{
addDataAndrChangeRow(nr.getRow(),nr.getColumn(),(int)nr.getValue(), debugger);
}
break;
//发现字符串类型,这儿要取字符串的值的话,跟据其index去字符串表里读取
case LabelSSTRecord.sid:
LabelSSTRecord lsr = (LabelSSTRecord)record;
addDataAndrChangeRow(lsr.getRow(),lsr.getColumn(), sstrec.getString(lsr.getSSTIndex()), debugger);
logger.debug( debugger, ">>>>>>>>>>文字列:"+sstrec.getString(lsr.getSSTIndex())+", 行:"+lsr.getRow()+", 列:"+lsr.getColumn());
break;
case BoolErrRecord.sid: //解析boolean错误信息
BoolErrRecord ber = (BoolErrRecord)record;
if(ber.isBoolean()){
addDataAndrChangeRow(ber.getRow(),ber.getColumn(), ber.getBooleanValue(), debugger);
logger.debug( debugger, ">>>>>>>>>>Boolean:"+ber.getBooleanValue()+", 行:"+ber.getRow()+", 列:"+ber.getColumn());
}
if(ber.isError()){
logger.debug( debugger, ">>>>>>>>>>Error:"+ber.getErrorValue()+", 行:"+ber.getRow()+", 列:"+ber.getColumn());
}
break;
//空白记录的信息
case BlankRecord.sid:
BlankRecord br = (BlankRecord)record;
addDataAndrChangeRow(br.getRow(),br.getColumn(), "", debugger);
logger.debug( debugger, ">>>>>>>>>>空。 行:"+br.getRow()+", 列:"+br.getColumn());
break;
case FormulaRecord.sid: //数式
FormulaRecord fr = (FormulaRecord)record;
addDataAndrChangeRow(fr.getRow(),fr.getColumn(), fr.getValue(), debugger);
logger.debug( debugger, ">>>>>>>>>>数字 。 行:"+fr.getRow()+", 列:"+fr.getColumn());
break;
}
}
/**
* HH:MM格式时间的数字转换方法</li>
* @param sNum
* @return
*/
private static String getTime(double daynum)
{
double totalSeconds=daynum*86400.0D;
//总的分钟数
int seconds =(int)totalSeconds/60;
//实际小时数
int hours =seconds/60;
int minutes = seconds-hours*60;
//剩余的实际分钟数
StringBuffer sb=new StringBuffer();
if(String.valueOf(hours).length()==1){
sb.append("0"+hours);
}else{
sb.append(hours);
}
sb.append(":");
if(String.valueOf(minutes).length()==1){
sb.append("0"+minutes);
}else{
sb.append(minutes);
}
return sb.toString();
}
/**
* 添加数据记录并检查是否换行
* @param row 实际当前行号
* @param col 实际记录当前列
* @param value 当前cell的值
*/
public void addDataAndrChangeRow( int row,int col,Object value, Boolean debugger ){
//当前行如果大于实际行表示改行忽略,不记录
if(curRowNum!=row){
if(CollectionUtils.isEmpty(currentSheetDataMap)){
currentSheetDataMap=new ArrayList<Map<String,Object>>();
}
currentSheetDataMap.add(currentSheetRowDataMap);
logger.debug( debugger, ">>>>>>>>>>行号:"+curRowNum +" 行内容:"+currentSheetRowDataMap.toString());
logger.debug( debugger, ">>>>>>>>>>\n");
currentSheetRowDataMap=new HashMap<String,Object>();
currentSheetRowDataMap.put(trianListheadTitle[col], value);
logger.debug( debugger, ">>>>>>>>>>"+ row+":"+col+" "+value+"\r");
curRowNum=row;
}else{
currentSheetRowDataMap.put(trianListheadTitle[col], value);
logger.debug(row+":"+col+" "+value+"\r");
}
}
public List<Map<String, Object>> getCurrentSheetDataMap() {
return currentSheetDataMap;
}
public void setCurrentSheetDataMap(List<Map<String, Object>> currentSheetDataMap) {
this.currentSheetDataMap = currentSheetDataMap;
}
public Map<String, Object> getCurrentSheetRowDataMap() {
return currentSheetRowDataMap;
}
public void setCurrentSheetRowDataMap(Map<String, Object> currentSheetRowDataMap) {
this.currentSheetRowDataMap = currentSheetRowDataMap;
}
public int getCurRowNum() {
return curRowNum;
}
public void setCurRowNum(int curRowNum) {
this.curRowNum = curRowNum;
}
public int getIgnoreRowNum() {
return ignoreRowNum;
}
public void setIgnoreRowNum(int ignoreRowNum) {
this.ignoreRowNum = ignoreRowNum;
}
public Boolean getDebugger() {
return debugger;
}
/**
* 是否开启调试日志
* @param debugger
*/
public void setDebugger(Boolean debugger) {
this.debugger = debugger;
}
}
package com.x.attendance.assemble.common.excel.writer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* 抽象excel2007读入器,先构建.xlsx一张模板,改写模板中的sheet.xml,使用这种方法
* 写入.xlsx文件,不需要太大的内存
*
*/
public abstract class AbstractExcel2007Writer {
private SpreadsheetWriter sw;
/**
* 写入电子表格的主要流程
* @param fileName
* @throws Exception
*/
public void process(String fileName) throws Exception{
// 建立工作簿和电子表格对象
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("sheet1");
// 持有电子表格数据的xml文件名 例如 /xl/worksheets/sheet1.xml
String sheetRef = sheet.getPackagePart().getPartName().getName();
// 保存模板
FileOutputStream os = new FileOutputStream("template.xlsx");
wb.write(os);
os.close();
// 生成xml文件
File tmp = File.createTempFile("sheet", ".xml");
Writer fw = new FileWriter(tmp);
sw = new SpreadsheetWriter(fw);
generate();
fw.close();
// 使用产生的数据替换模板
File templateFile = new File("template.xlsx");
FileOutputStream out = new FileOutputStream(fileName);
substitute(templateFile, tmp, sheetRef.substring(1), out);
out.close();
//删除文件之前调用一下垃圾回收器,否则无法删除模板文件
System.gc();
// 删除临时模板文件
if (templateFile.isFile()&&templateFile.exists()){
templateFile.delete();
}
}
/**
* 类使用者应该使用此方法进行写操作
* @throws Exception
*/
public abstract void generate() throws Exception;
public void beginSheet() throws IOException {
sw.beginSheet();
}
public void insertRow(int rowNum) throws IOException {
sw.insertRow(rowNum);
}
public void createCell(int columnIndex, String value) throws IOException {
sw.createCell(columnIndex, value, -1);
}
public void createCell(int columnIndex, double value) throws IOException {
sw.createCell(columnIndex, value, -1);
}
public void endRow() throws IOException {
sw.endRow();
}
public void endSheet() throws IOException {
sw.endSheet();
}
/**
*
* @param zipfile the template file
* @param tmpfile the XML file with the sheet data
* @param entry the name of the sheet entry to substitute, e.g. xl/worksheets/sheet1.xml
* @param out the stream to write the result to
*/
private static void substitute(File zipfile, File tmpfile, String entry,
OutputStream out) throws IOException {
ZipFile zip = new ZipFile(zipfile);
ZipOutputStream zos = new ZipOutputStream(out);
@SuppressWarnings("unchecked")
Enumeration<ZipEntry> en = (Enumeration<ZipEntry>) zip.entries();
while (en.hasMoreElements()) {
ZipEntry ze = en.nextElement();
if (!ze.getName().equals(entry)) {
zos.putNextEntry(new ZipEntry(ze.getName()));
InputStream is = zip.getInputStream(ze);
copyStream(is, zos);
is.close();
}
}
zos.putNextEntry(new ZipEntry(entry));
InputStream is = new FileInputStream(tmpfile);
copyStream(is, zos);
is.close();
zos.close();
}
private static void copyStream(InputStream in, OutputStream out)
throws IOException {
byte[] chunk = new byte[1024];
int count;
while ((count = in.read(chunk)) >= 0) {
out.write(chunk, 0, count);
}
}
/**
* 在写入器中写入电子表格
*
*/
public static class SpreadsheetWriter {
private final Writer _out;
private int _rownum;
private static String LINE_SEPARATOR = System.getProperty("line.separator");
public SpreadsheetWriter(Writer out) {
_out = out;
}
public void beginSheet() throws IOException {
_out.write("<?xml version=\"1.0\" encoding=\"GB2312\"?>"
+ "<worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">");
_out.write("<sheetData>"+LINE_SEPARATOR);
}
public void endSheet() throws IOException {
_out.write("</sheetData>");
_out.write("</worksheet>");
}
/**
* 插入新行
*
* @param rownum 以0开始
*/
public void insertRow(int rownum) throws IOException {
_out.write("<row r=\"" + (rownum + 1) + "\">"+LINE_SEPARATOR);
this._rownum = rownum;
}
/**
* 插入行结束标志
*/
public void endRow() throws IOException {
_out.write("</row>"+LINE_SEPARATOR);
}
/**
* 插入新列
* @param columnIndex
* @param value
* @param styleIndex
* @throws IOException
*/
public void createCell(int columnIndex, String value, int styleIndex)
throws IOException {
String ref = new CellReference(_rownum, columnIndex)
.formatAsString();
_out.write("<c r=\"" + ref + "\" t=\"inlineStr\"");
if (styleIndex != -1)
_out.write(" s=\"" + styleIndex + "\"");
_out.write(">");
_out.write("<is><t>"+XMLEncoder.encode(value)+"</t></is>");
_out.write("</c>");
}
public void createCell(int columnIndex, String value)
throws IOException {
createCell(columnIndex, value, -1);
}
public void createCell(int columnIndex, double value, int styleIndex)
throws IOException {
String ref = new CellReference(_rownum, columnIndex)
.formatAsString();
_out.write("<c r=\"" + ref + "\" t=\"n\"");
if (styleIndex != -1)
_out.write(" s=\"" + styleIndex + "\"");
_out.write(">");
_out.write("<v>" + value + "</v>");
_out.write("</c>");
}
public void createCell(int columnIndex, double value)
throws IOException {
createCell(columnIndex, value, -1);
}
public void createCell(int columnIndex, Calendar value, int styleIndex)
throws IOException {
createCell(columnIndex, DateUtil.getExcelDate(value, false),
styleIndex);
}
}
}
\ No newline at end of file
package com.x.attendance.assemble.common.excel.writer;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
public class Excel2003Writer {
/**
* @param args
*/
public static void main(String[] args) {
try{
writeExcel("tes2003.xls");
} catch (IOException e) {
}
}
/**
* 写入excel并填充内容,一个sheet只能写65536行以下,超出会报异常,写入时建议使用AbstractExcel2007Writer
* @param fileName
* @throws IOException
*/
public static void writeExcel(String fileName) throws IOException{
// 创建excel2003对象
Workbook wb = new HSSFWorkbook();
// 设置文件放置路径和文件名
FileOutputStream fileOut = new FileOutputStream(fileName);
// 创建新的表单
Sheet sheet = wb.createSheet("newsheet");
// 创建新行
for(int i=0;i<20000;i++){
Row row = sheet.createRow(i);
// 创建单元格
Cell cell = row.createCell(0);
// 设置单元格值
cell.setCellValue(1);
row.createCell(1).setCellValue(1+i);
row.createCell(2).setCellValue(true);
row.createCell(3).setCellValue(0.43d);
row.createCell(4).setCellValue('d');
row.createCell(5).setCellValue("");
row.createCell(6).setCellValue("第七列"+i);
row.createCell(7).setCellValue("第八列"+i);
}
wb.write(fileOut);
fileOut.close();
}
}
package com.x.attendance.assemble.common.excel.writer;
public class Excel2007WriterImpl extends AbstractExcel2007Writer{
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
//构建excel2007写入器
AbstractExcel2007Writer excel07Writer = new Excel2007WriterImpl();
//调用处理方法
excel07Writer.process("F://test07.xlsx");
}
/*
* 可根据需求重写此方法,对于单元格的小数或者日期格式,会出现精度问题或者日期格式转化问题,建议使用字符串插入方法
* @see com.excel.ver2.AbstractExcel2007Writer#generate()
*/
@Override
public void generate()throws Exception {
//电子表格开始
beginSheet();
for (int rownum = 0; rownum < 100; rownum++) {
//插入新行
insertRow(rownum);
//建立新单元格,索引值从0开始,表示第一列
createCell(0, "中国<" + rownum + "!");
createCell(1, 34343.123456789);
createCell(2, "23.67%");
createCell(3, "12:12:23");
createCell(4, "2010-10-11 12:12:23");
createCell(5, "true");
createCell(6, "false");
//结束行
endRow();
}
//电子表格结束
endSheet();
}
}
package com.x.attendance.assemble.common.excel.writer;
public class XMLEncoder {
private static final String[] xmlCode = new String[256];
static {
// Special characters
xmlCode['\''] = "'";
xmlCode['\"'] = "\""; // double quote
xmlCode['&'] = "&"; // ampersand
xmlCode['<'] = "<"; // lower than
xmlCode['>'] = ">"; // greater than
}
/**
* <p>
* Encode the given text into xml.
* </p>
*
* @param string the text to encode
* @return the encoded string
*/
public static String encode(String string) {
if (string == null) return "";
int n = string.length();
char character;
String xmlchar;
StringBuffer buffer = new StringBuffer();
// loop over all the characters of the String.
for (int i = 0; i < n; i++) {
character = string.charAt(i);
// the xmlcode of these characters are added to a StringBuffer one by one
try {
xmlchar = xmlCode[character];
if (xmlchar == null) {
buffer.append(character);
} else {
buffer.append(xmlCode[character]);
}
} catch (ArrayIndexOutOfBoundsException aioobe) {
buffer.append(character);
}
}
return buffer.toString();
}
}
package com.x.attendance.assemble.control;
import com.x.base.core.container.EntityManagerContainer;
public abstract class AbstractFactory {
private Business business;
public AbstractFactory( Business business ) throws Exception {
try {
if ( null == business ) {
throw new Exception("business can not be null.");
}
this.business = business;
} catch ( Exception e ) {
throw new Exception("can not instantiating factory.");
}
}
public EntityManagerContainer entityManagerContainer() throws Exception {
return this.business.entityManagerContainer();
}
}
\ No newline at end of file
package com.x.attendance.assemble.control;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import com.x.base.core.project.Context;
@WebListener
public class ApplicationServletContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
try {
ThisApplication.context = Context.concrete(servletContextEvent);
ThisApplication.init();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
try {
ThisApplication.destroy();
ThisApplication.context.destrory(servletContextEvent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
\ No newline at end of file
package com.x.attendance.assemble.control;
import com.x.attendance.assemble.control.factory.AttendanceAdminFactory;
import com.x.attendance.assemble.control.factory.AttendanceAppealInfoFactory;
import com.x.attendance.assemble.control.factory.AttendanceDetailFactory;
import com.x.attendance.assemble.control.factory.AttendanceDetailMobileFactory;
import com.x.attendance.assemble.control.factory.AttendanceDetailStatisticFactory;
import com.x.attendance.assemble.control.factory.AttendanceEmployeeConfigFactory;
import com.x.attendance.assemble.control.factory.AttendanceImportFileInfoFactory;
import com.x.attendance.assemble.control.factory.AttendanceScheduleSettingFactory;
import com.x.attendance.assemble.control.factory.AttendanceSelfHolidayFactory;
import com.x.attendance.assemble.control.factory.AttendanceSettingFactory;
import com.x.attendance.assemble.control.factory.AttendanceStatisticRequireLogFactory;
import com.x.attendance.assemble.control.factory.AttendanceStatisticalCycleFactory;
import com.x.attendance.assemble.control.factory.AttendanceWorkDayConfigFactory;
import com.x.attendance.assemble.control.factory.AttendanceWorkPlaceFactory;
import com.x.attendance.assemble.control.factory.StatisticPersonForMonthFactory;
import com.x.attendance.assemble.control.factory.StatisticTopUnitForDayFactory;
import com.x.attendance.assemble.control.factory.StatisticTopUnitForMonthFactory;
import com.x.attendance.assemble.control.factory.StatisticUnitForDayFactory;
import com.x.attendance.assemble.control.factory.StatisticUnitForMonthFactory;
import com.x.base.core.container.EntityManagerContainer;
import com.x.organization.core.express.Organization;
public class Business {
private EntityManagerContainer emc;
public Business(EntityManagerContainer emc) throws Exception {
this.emc = emc;
}
public EntityManagerContainer entityManagerContainer() {
return this.emc;
}
// 人员组织业务处理类
private Organization organization;
// 系统配置业务处理类
private AttendanceSettingFactory attendanceSettingFactory;
// 工作场所配置业务处理类
private AttendanceWorkPlaceFactory attendanceWorkPlaceFactory;
// 节假日工作日配置业务处理类
private AttendanceWorkDayConfigFactory attendanceWorkDayConfigFactory;
// 人员考勤数据导入文件操作业务处理类
private AttendanceImportFileInfoFactory attendanceImportFileInfoFactory;
// 人员考勤数据业务处理类
private AttendanceDetailFactory attendanceDetailFactory;
private AttendanceDetailMobileFactory attendanceDetailMobileFactory;
// 考勤管理员业务处理类
private AttendanceAdminFactory attendanceAdminFactory;
// 排班管理业务处理类
private AttendanceScheduleSettingFactory attendanceScheduleSettingFactory;
// 休假申请数据业务处理类
private AttendanceSelfHolidayFactory attendanceSelfHolidayFactory;
private StatisticTopUnitForDayFactory statisticTopUnitForDayFactory;
private StatisticTopUnitForMonthFactory statisticTopUnitForMonthFactory;
private StatisticUnitForDayFactory statisticUnitForDayFactory;
private StatisticUnitForMonthFactory statisticUnitForMonthFactory;
private StatisticPersonForMonthFactory statisticPersonForMonthFactory;
private AttendanceAppealInfoFactory attendanceAppealInfoFactory;
private AttendanceStatisticalCycleFactory attendanceStatisticalCycleFactory;
private AttendanceEmployeeConfigFactory attendanceEmployeeConfigFactory;
private AttendanceStatisticRequireLogFactory attendanceStatisticRequireLogFactory;
private AttendanceDetailStatisticFactory attendanceDetailStatisticFactory;
public AttendanceWorkPlaceFactory attendanceWorkPlaceFactory() throws Exception {
if (null == this.attendanceWorkPlaceFactory) {
this.attendanceWorkPlaceFactory = new AttendanceWorkPlaceFactory(this);
}
return attendanceWorkPlaceFactory;
}
public AttendanceDetailMobileFactory getAttendanceDetailMobileFactory() throws Exception {
if (null == this.attendanceDetailMobileFactory) {
this.attendanceDetailMobileFactory = new AttendanceDetailMobileFactory(this);
}
return attendanceDetailMobileFactory;
}
public AttendanceDetailStatisticFactory getAttendanceDetailStatisticFactory() throws Exception {
if (null == this.attendanceDetailStatisticFactory) {
this.attendanceDetailStatisticFactory = new AttendanceDetailStatisticFactory(this);
}
return attendanceDetailStatisticFactory;
}
public AttendanceEmployeeConfigFactory getAttendanceEmployeeConfigFactory() throws Exception {
if (null == this.attendanceEmployeeConfigFactory) {
this.attendanceEmployeeConfigFactory = new AttendanceEmployeeConfigFactory(this);
}
return attendanceEmployeeConfigFactory;
}
public AttendanceStatisticRequireLogFactory getAttendanceStatisticRequireLogFactory() throws Exception {
if (null == this.attendanceStatisticRequireLogFactory) {
this.attendanceStatisticRequireLogFactory = new AttendanceStatisticRequireLogFactory(this);
}
return attendanceStatisticRequireLogFactory;
}
public AttendanceStatisticalCycleFactory getAttendanceStatisticalCycleFactory() throws Exception {
if (null == this.attendanceStatisticalCycleFactory) {
this.attendanceStatisticalCycleFactory = new AttendanceStatisticalCycleFactory(this);
}
return attendanceStatisticalCycleFactory;
}
public AttendanceAppealInfoFactory getAttendanceAppealInfoFactory() throws Exception {
if (null == this.attendanceAppealInfoFactory) {
this.attendanceAppealInfoFactory = new AttendanceAppealInfoFactory(this);
}
return attendanceAppealInfoFactory;
}
public StatisticTopUnitForDayFactory getStatisticTopUnitForDayFactory() throws Exception {
if (null == this.statisticTopUnitForDayFactory) {
this.statisticTopUnitForDayFactory = new StatisticTopUnitForDayFactory(this);
}
return statisticTopUnitForDayFactory;
}
public StatisticTopUnitForMonthFactory getStatisticTopUnitForMonthFactory() throws Exception {
if (null == this.statisticTopUnitForMonthFactory) {
this.statisticTopUnitForMonthFactory = new StatisticTopUnitForMonthFactory(this);
}
return statisticTopUnitForMonthFactory;
}
public StatisticUnitForDayFactory getStatisticUnitForDayFactory() throws Exception {
if (null == this.statisticUnitForDayFactory) {
this.statisticUnitForDayFactory = new StatisticUnitForDayFactory(this);
}
return statisticUnitForDayFactory;
}
public StatisticUnitForMonthFactory getStatisticUnitForMonthFactory() throws Exception {
if (null == this.statisticUnitForMonthFactory) {
this.statisticUnitForMonthFactory = new StatisticUnitForMonthFactory(this);
}
return statisticUnitForMonthFactory;
}
public StatisticPersonForMonthFactory getStatisticPersonForMonthFactory() throws Exception {
if (null == this.statisticPersonForMonthFactory) {
this.statisticPersonForMonthFactory = new StatisticPersonForMonthFactory(this);
}
return statisticPersonForMonthFactory;
}
public Organization organization() throws Exception {
if (null == this.organization) {
this.organization = new Organization(ThisApplication.context());
}
return organization;
}
public AttendanceSettingFactory getAttendanceSettingFactory() throws Exception {
if (null == this.attendanceSettingFactory) {
this.attendanceSettingFactory = new AttendanceSettingFactory(this);
}
return attendanceSettingFactory;
}
public AttendanceWorkDayConfigFactory getAttendanceWorkDayConfigFactory() throws Exception {
if (null == this.attendanceWorkDayConfigFactory) {
this.attendanceWorkDayConfigFactory = new AttendanceWorkDayConfigFactory(this);
}
return attendanceWorkDayConfigFactory;
}
public AttendanceImportFileInfoFactory getAttendanceImportFileInfoFactory() throws Exception {
if (null == this.attendanceImportFileInfoFactory) {
this.attendanceImportFileInfoFactory = new AttendanceImportFileInfoFactory(this);
}
return attendanceImportFileInfoFactory;
}
public AttendanceDetailFactory getAttendanceDetailFactory() throws Exception {
if (null == this.attendanceDetailFactory) {
this.attendanceDetailFactory = new AttendanceDetailFactory(this);
}
return attendanceDetailFactory;
}
public AttendanceAdminFactory getAttendanceAdminFactory() throws Exception {
if (null == this.attendanceAdminFactory) {
this.attendanceAdminFactory = new AttendanceAdminFactory(this);
}
return attendanceAdminFactory;
}
public AttendanceScheduleSettingFactory getAttendanceScheduleSettingFactory() throws Exception {
if (null == this.attendanceScheduleSettingFactory) {
this.attendanceScheduleSettingFactory = new AttendanceScheduleSettingFactory(this);
}
return attendanceScheduleSettingFactory;
}
public AttendanceSelfHolidayFactory getAttendanceSelfHolidayFactory() throws Exception {
if (null == this.attendanceSelfHolidayFactory) {
this.attendanceSelfHolidayFactory = new AttendanceSelfHolidayFactory(this);
}
return attendanceSelfHolidayFactory;
}
}
package com.x.attendance.assemble.control;
import com.x.base.core.entity.JpaObject;
import com.x.base.core.project.cache.ApplicationCache;
/**
* 缓存管理帮助类
* @author liyi
*
*/
public class CacheUtil {
public static <T extends JpaObject> void notify( Class<T> clz ) throws Exception {
ApplicationCache.notify( clz );
}
}
package com.x.attendance.assemble.control;
import com.google.gson.JsonElement;
import com.x.base.core.project.exception.PromptException;
public class ExceptionWrapInConvert extends PromptException {
private static final long serialVersionUID = 1859164370743532895L;
public ExceptionWrapInConvert( Throwable e, JsonElement jsonElement) {
super( "系统在将JSON信息转换为对象时发生异常。JSON:" + jsonElement.toString(), e);
}
}
package com.x.attendance.assemble.control;
import javax.activation.MimetypesFileTypeMap;
public class MimeTypeDefinition {
public static MimetypesFileTypeMap instance;
}
package com.x.attendance.assemble.control;
import com.x.attendance.assemble.control.processor.monitor.MonitorFileDataOpt;
import com.x.attendance.assemble.control.processor.thread.DataProcessThreadFactory;
import com.x.attendance.assemble.control.schedule.AttendanceStatisticTask;
import com.x.attendance.assemble.control.schedule.MobileRecordAnalyseTask;
import com.x.attendance.assemble.control.service.AttendanceSettingService;
import com.x.base.core.project.Context;
public class ThisApplication {
protected static Context context;
public static Context context() {
return context;
}
public static void init() throws Exception {
try {
new AttendanceSettingService().initAllSystemConfig();
context.schedule(AttendanceStatisticTask.class, "0 0 0/4 * * ?");
context.schedule(MobileRecordAnalyseTask.class, "0 0 1/4 * * ?");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void destroy() {
try {
DataProcessThreadFactory.getInstance().showdown();
} catch (Exception e) {
e.printStackTrace();
}
try {
MonitorFileDataOpt.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.x.attendance.assemble.control.exception;
import com.x.base.core.project.exception.PromptException;
public class PersonHasNoIdentityException extends PromptException {
private static final long serialVersionUID = 1859164370743532895L;
public PersonHasNoIdentityException() {
super("用户未分配任何身份,请检查用户所在的组织信息。");
}
public PersonHasNoIdentityException( String name ) {
super("用户'"+ name +"'未分配任何身份,请检查用户所在的组织信息。");
}
}
\ No newline at end of file
package com.x.attendance.assemble.control.factory;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import com.x.attendance.assemble.control.AbstractFactory;
import com.x.attendance.assemble.control.Business;
import com.x.attendance.entity.AttendanceAdmin;
import com.x.attendance.entity.AttendanceAdmin_;
import com.x.base.core.project.exception.ExceptionWhen;
/**
* 系统配置信息表基础功能服务类
* @author liyi
*/
public class AttendanceAdminFactory extends AbstractFactory {
public AttendanceAdminFactory(Business business) throws Exception {
super(business);
}
//@MethodDescribe("获取指定Id的AttendanceAdmin应用信息对象")
public AttendanceAdmin get( String id ) throws Exception {
return this.entityManagerContainer().find(id, AttendanceAdmin.class, ExceptionWhen.none);
}
//@MethodDescribe("列示全部的AttendanceAdmin应用信息列表")
public List<AttendanceAdmin> listAll() throws Exception {
EntityManager em = this.entityManagerContainer().get(AttendanceAdmin.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<AttendanceAdmin> cq = cb.createQuery(AttendanceAdmin.class);
Root<AttendanceAdmin> root = cq.from( AttendanceAdmin.class);
return em.createQuery(cq).getResultList();
}
//@MethodDescribe("列示指定Id的AttendanceAdmin应用信息列表")
public List<AttendanceAdmin> list(List<String> ids) throws Exception {
if( ids == null || ids.size() == 0 ){
return new ArrayList<AttendanceAdmin>();
}
EntityManager em = this.entityManagerContainer().get(AttendanceAdmin.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<AttendanceAdmin> cq = cb.createQuery(AttendanceAdmin.class);
Root<AttendanceAdmin> root = cq.from(AttendanceAdmin.class);
Predicate p = root.get(AttendanceAdmin_.id).in(ids);
return em.createQuery(cq.where(p)).getResultList();
}
}
\ No newline at end of file
package com.x.attendance.assemble.control.factory;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import com.x.attendance.assemble.control.AbstractFactory;
import com.x.attendance.assemble.control.Business;
import com.x.attendance.entity.AttendanceDetailMobile;
import com.x.attendance.entity.AttendanceDetailMobile_;
/**
* 系统配置信息表基础功能服务类
* @author liyi
*/
public class AttendanceDetailMobileFactory extends AbstractFactory {
public AttendanceDetailMobileFactory( Business business ) throws Exception {
super(business);
}
public List<String> listByEmployeeNameDateAndTime( String empName, String recordDateString, String signTime ) throws Exception {
if( empName == null || empName.isEmpty() ){
throw new Exception("empName is null!");
}
if( recordDateString == null || recordDateString.isEmpty() ){
throw new Exception("recordDateString is null!");
}
if( signTime == null || signTime.isEmpty() ){
throw new Exception("signTime is null!");
}
EntityManager em = this.entityManagerContainer().get(AttendanceDetailMobile.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<AttendanceDetailMobile> root = cq.from( AttendanceDetailMobile.class);
cq.select(root.get(AttendanceDetailMobile_.id));
Predicate p = cb.equal( root.get(AttendanceDetailMobile_.empName), empName );
p = cb.and( p, cb.equal( root.get(AttendanceDetailMobile_.recordDateString ), recordDateString ) );
p = cb.and( p, cb.equal( root.get(AttendanceDetailMobile_.signTime ), signTime ) );
return em.createQuery(cq.where( p )).getResultList();
}
//@MethodDescribe("列示指定Id的AttendanceDetailMobile信息列表")
public List<AttendanceDetailMobile> list(List<String> ids) throws Exception {
List<AttendanceDetailMobile> resultList = null;
if( ids == null || ids.size() == 0 ){
throw new Exception("ids is null!");
}
EntityManager em = this.entityManagerContainer().get(AttendanceDetailMobile.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<AttendanceDetailMobile> cq = cb.createQuery(AttendanceDetailMobile.class);
Root<AttendanceDetailMobile> root = cq.from(AttendanceDetailMobile.class);
Predicate p = root.get( AttendanceDetailMobile_.id).in( ids );
resultList = em.createQuery( cq.where(p) ).getResultList();
return resultList;
}
public Long countAttendanceDetailMobileForPage( String empNo, String empName, String signDescription,
String startDate, String endDate) throws Exception {
EntityManager em = this.entityManagerContainer().get( AttendanceDetailMobile.class );
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
Root<AttendanceDetailMobile> root = cq.from(AttendanceDetailMobile.class);
Predicate p = cb.isNotNull( root.get( AttendanceDetailMobile_.id ) );
if( empNo != null && !empNo.isEmpty() ){
p = cb.and( p, cb.equal( root.get( AttendanceDetailMobile_.empNo ), empNo ) );
}
if( empName != null && !empName.isEmpty() ){
p = cb.and( p, cb.equal( root.get( AttendanceDetailMobile_.empName ), empName ) );
}
if( signDescription != null && !signDescription.isEmpty() ){
p = cb.and( p, cb.equal( root.get( AttendanceDetailMobile_.signDescription ), signDescription ) );
}
if( startDate != null && !startDate.isEmpty() ){
if( endDate != null && !endDate.isEmpty() && !endDate.equals( startDate ) ){//查询日期区间
p = cb.between( root.get( AttendanceDetailMobile_.recordDateString ), startDate, endDate );
}else{
//查询startDate当天
p = cb.and( p, cb.equal( root.get( AttendanceDetailMobile_.recordDateString ), startDate ) );
}
}
cq.select( cb.count( root ) );
return em.createQuery(cq.where(p)).getSingleResult();
}
public List<AttendanceDetailMobile> listAttendanceDetailMobileForPage( String empNo, String empName, String signDescription,
String startDate, String endDate, Integer selectTotal ) throws Exception {
if( selectTotal == null ){
selectTotal = 100;
}
EntityManager em = this.entityManagerContainer().get( AttendanceDetailMobile.class );
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<AttendanceDetailMobile> cq = cb.createQuery(AttendanceDetailMobile.class);
Root<AttendanceDetailMobile> root = cq.from(AttendanceDetailMobile.class);
Predicate p = cb.isNotNull( root.get( AttendanceDetailMobile_.id ) );
if( empNo != null && !empNo.isEmpty() ){
p = cb.and( p, cb.equal( root.get( AttendanceDetailMobile_.empNo ), empNo ) );
}
if( empName != null && !empName.isEmpty() ){
p = cb.and( p, cb.equal( root.get( AttendanceDetailMobile_.empName ), empName ) );
}
if( signDescription != null && !signDescription.isEmpty() ){
p = cb.and( p, cb.equal( root.get( AttendanceDetailMobile_.signDescription ), signDescription ) );
}
if( startDate != null && !startDate.isEmpty() ){
if( endDate != null && !endDate.isEmpty() && !endDate.equals( startDate ) ){//查询日期区间
p = cb.between( root.get( AttendanceDetailMobile_.recordDateString ), startDate, endDate );
}else{
//查询startDate当天
p = cb.and( p, cb.equal( root.get( AttendanceDetailMobile_.recordDateString ), startDate ) );
}
}
return em.createQuery(cq.where(p)).setMaxResults( selectTotal ).getResultList();
}
public AttendanceDetailMobile get(String id) throws Exception {
return this.entityManagerContainer().find(id, AttendanceDetailMobile.class );
}
public List<String> listAllAnalyseWithStatus(int status) throws Exception {
EntityManager em = this.entityManagerContainer().get(AttendanceDetailMobile.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<AttendanceDetailMobile> root = cq.from( AttendanceDetailMobile.class);
cq.select(root.get(AttendanceDetailMobile_.id));
Predicate p = cb.equal( root.get(AttendanceDetailMobile_.recordStatus), status );
return em.createQuery(cq.where( p )).getResultList();
}
}
\ No newline at end of file
package com.x.attendance.assemble.control.factory;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import com.x.attendance.assemble.control.AbstractFactory;
import com.x.attendance.assemble.control.Business;
import com.x.attendance.entity.AttendanceEmployeeConfig;
import com.x.attendance.entity.AttendanceEmployeeConfig_;
import com.x.base.core.project.exception.ExceptionWhen;
/**
* 员工考勤需求配置服务器
* @author liyi
*/
public class AttendanceEmployeeConfigFactory extends AbstractFactory {
public AttendanceEmployeeConfigFactory(Business business) throws Exception {
super(business);
}
// @MethodDescribe("获取指定Id的AttendanceEmployeeConfig信息对象")
public AttendanceEmployeeConfig get( String id ) throws Exception {
return this.entityManagerContainer().find(id, AttendanceEmployeeConfig.class, ExceptionWhen.none);
}
//@MethodDescribe("列示全部的AttendanceEmployeeConfig信息列表")
public List<AttendanceEmployeeConfig> listAll() throws Exception {
EntityManager em = this.entityManagerContainer().get(AttendanceEmployeeConfig.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<AttendanceEmployeeConfig> cq = cb.createQuery(AttendanceEmployeeConfig.class);
Root<AttendanceEmployeeConfig> root = cq.from( AttendanceEmployeeConfig.class);
return em.createQuery(cq).getResultList();
}
//@MethodDescribe("列示指定Id的AttendanceEmployeeConfig信息列表")
public List<AttendanceEmployeeConfig> list(List<String> ids) throws Exception {
if( ids == null || ids.size() == 0 ){
return new ArrayList<AttendanceEmployeeConfig>();
}
EntityManager em = this.entityManagerContainer().get(AttendanceEmployeeConfig.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<AttendanceEmployeeConfig> cq = cb.createQuery(AttendanceEmployeeConfig.class);
Root<AttendanceEmployeeConfig> root = cq.from(AttendanceEmployeeConfig.class);
Predicate p = root.get(AttendanceEmployeeConfig_.id).in(ids);
return em.createQuery(cq.where(p)).getResultList();
}
//@MethodDescribe("根据配置类别列示AttendanceEmployeeConfig信息列表")
public List<String> listByConfigType( String configType ) throws Exception {
if( configType == null || configType.isEmpty()){
return new ArrayList<String>();
}
EntityManager em = this.entityManagerContainer().get(AttendanceEmployeeConfig.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<AttendanceEmployeeConfig> root = cq.from(AttendanceEmployeeConfig.class);
Predicate p = cb.equal(root.get(AttendanceEmployeeConfig_.configType), configType);
cq.select(root.get(AttendanceEmployeeConfig_.id));
return em.createQuery(cq.where(p)).getResultList();
}
}
\ No newline at end of file
package com.x.attendance.assemble.control.factory;
import com.x.base.core.project.exception.PromptException;
class CycleMonthEmptyException extends PromptException {
private static final long serialVersionUID = 1859164370743532895L;
CycleMonthEmptyException() {
super("统计月份不能为空.");
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册