码迷,mamicode.com
首页 > 其他好文 > 详细

poi

时间:2018-02-08 19:59:19      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:返回   service   except   get   failure   scom   +=   list   .class   

========================================================   Controller =======================================================
@RequestMapping("/executeOperateFund")
@ResponseBody
public InvokeResult executeOperateFund(){
String file = "excel/total/import_data_total_opera.xls";
String url = Thread.currentThread().getContextClassLoader().getResource(file).getPath();
try{
InputStream input = new FileInputStream(url);
String message =excelImportService.importOperationFundExcel(input,file);
return InvokeResult.success(message);
}catch (Exception e){
LOGGER.error(e.getMessage());
return InvokeResult.failure(e.getMessage());
}
}
============================================ 以下为service ===========================================================

@Service
@Transactional
public class ExcelImportServiceImpl extends ServiceSupport implements ExcelImportService {

private SingleEntityManager<ProjectDeclaration> projectInternal = RepositoryFactory.get().build(ProjectDeclaration.class);
private SingleEntityManager<TaskManagement> taskInternal = RepositoryFactory.get().build(TaskManagement.class);
private SingleEntityManager<Contract> contractInternal = RepositoryFactory.get().build(Contract.class);
private SingleEntityManager<Audit> auditInternal = RepositoryFactory.get().build(Audit.class);
private SingleEntityManager<FundPayment> fundPaymentInternal = RepositoryFactory.get().build(FundPayment.class);

@Autowired
private ProjectRecordService projectRecordService;

@Autowired
private OperationFundService operationFundService;

@Autowired
private TreeMenuService treeMenuService;

@Override
public String importExcel(InputStream inputStream, String fileName) throws Exception{

String message = "Import success";

boolean isE2007 = false;
//判断是否是excel2007格式
if(fileName.endsWith("xlsx")){
isE2007 = true;
}
int rowIndex = 0;

try {
InputStream input = inputStream;
Workbook wb;
if(isE2007){
wb = new XSSFWorkbook(input);
}else{
wb = new HSSFWorkbook(input);
}
Sheet sheet = wb.getSheetAt(0);

int rowCount = sheet.getLastRowNum()+1;

rowIndex = importExcel(sheet,rowCount,10,true);

} catch (Exception ex) {
message = "Import failed, please check the data in "+rowIndex+" rows ";
}
return message;
}

public int importExcel(Sheet sheet,int rowCount, int i,boolean isProject) throws Exception{

int rowIndex = i;
List<CellRangeAddress> cras = getCombineCell(sheet);

for (; i <= rowCount; i++) {
rowIndex = i;
Row row = sheet.getRow(i);


//建设单位为合并单元格
if (isMergedRegion(sheet, i, 0)) {
int lastRow = getRowNum(cras, sheet.getRow(i).getCell(0), sheet);
for (; i <= lastRow; i++) {

//项目名称为合并的单元格
if (isMergedRegion(sheet, i, 2)) {

i--;
} else {
//业务逻辑
}
}
i--;
rowIndex = i;
} else {
            //业务逻辑

}
}

return rowIndex;
}

public String importOperationFundExcel(InputStream inputStream, String fileName) throws Exception{
String message = "Import success";

boolean isE2007 = false;
//判断是否是excel2007格式
if(fileName.endsWith("xlsx")){
isE2007 = true;
}

int rowIndex = 0;
try {
InputStream input = inputStream; //建立输入流
Workbook wb;
//根据文件格式(2003或者2007)来初始化
if(isE2007){
wb = new XSSFWorkbook(input);
}else{
wb = new HSSFWorkbook(input);
}
Sheet sheet = wb.getSheetAt(0); //获得第一个表单
List<CellRangeAddress> cras = getCombineCell(sheet);
int rowCount = sheet.getLastRowNum()+1;

for(int i = 1; i < rowCount;i++){
rowIndex = i;
Row row = sheet.getRow(i);
String companyName = getValue(sheet,i,0);
String companyCode = getValue(sheet,i,1);

//建设单位为合并单元格
if(isMergedRegion(sheet,i,0)){
int lastRow = getRowNum(cras,sheet.getRow(i).getCell(0),sheet);
for(;i<=lastRow;i++){
//项目名称为合并的单元格
if(isMergedRegion(sheet,i,2)){
//操作项目
int subLastRow = getRowNum(cras,sheet.getRow(i).getCell(2),sheet);
//新增运行资金
for(;i<=subLastRow;i++){
saveOperateFund(sheet,i);
}
i--;
}else{
saveOperateFund(sheet,i);
}
}
i--;
}else{
saveOperateFund(sheet,i);
}

}
} catch (Exception ex) {
message = "Import failed, please check the data in "+rowIndex+" rows ";
}
return message;

}






/**
* 返回dateStr的月初(如果dateStr小于本月份 返回本月月初)
*
*/
public Date conventStringToDate(String dateStr){

SimpleDateFormat sdf =new SimpleDateFormat("yyyyMM");
SimpleDateFormat sdf2 =new SimpleDateFormat("yyyy");
SimpleDateFormat sd3 = new SimpleDateFormat("yyyyMMdd");
if(null != dateStr && StringUtils.isNotBlank(dateStr)){
try {
Date result1 = sd3.parse(dateStr);
return result1;
} catch (ParseException e) {
try{
Date result = sdf.parse(dateStr);
return result;
}catch(ParseException e2){
try{
return sdf2.parse(dateStr);
}catch (ParseException e3){
e.printStackTrace();
}
}
}
}
return null;
}

/**
* 获取单元格的值
* @return
*/
public String getValue(Sheet sheet,int i,int j){

if(isMergedRegion(sheet,i,j)){
return getMergedRegionValue(sheet,i,j);
}else{
Row row = sheet.getRow(i);
return row.getCell(j).getStringCellValue();
}
}



/**
* 获取单元格的值
* @param cell
* @return
*/
public String getCellValue(Cell cell){
if(cell == null) return "";
return cell.getStringCellValue();
}


/**
* 合并单元格处理,获取合并行
* @param sheet
* @return List<CellRangeAddress>
*/
public List<CellRangeAddress> getCombineCell(Sheet sheet)
{
List<CellRangeAddress> list = new ArrayList<>();
//获得一个 sheet 中合并单元格的数量
int sheetmergerCount = sheet.getNumMergedRegions();
//遍历所有的合并单元格
for(int i = 0; i<sheetmergerCount;i++)
{
//获得合并单元格保存进list中
CellRangeAddress ca = sheet.getMergedRegion(i);
list.add(ca);
}
return list;
}

private int getRowNum(List<CellRangeAddress> listCombineCell,Cell cell,Sheet sheet){
int xr = 0;
int firstC = 0;
int lastC = 0;
int firstR = 0;
int lastR = 0;
for(CellRangeAddress ca:listCombineCell)
{
//获得合并单元格的起始行, 结束行, 起始列, 结束列
firstC = ca.getFirstColumn();
lastC = ca.getLastColumn();
firstR = ca.getFirstRow();
lastR = ca.getLastRow();
if(cell.getRowIndex() >= firstR && cell.getRowIndex() <= lastR)
{
if(cell.getColumnIndex() >= firstC && cell.getColumnIndex() <= lastC)
{
xr = lastR;
}
}

}
return xr;

}
/**
* 判断单元格是否为合并单元格,是的话则将单元格的值返回
* @param listCombineCell 存放合并单元格的list
* @param cell 需要判断的单元格
* @param sheet sheet
* @return
*/
public String isCombineCell(List<CellRangeAddress> listCombineCell,Cell cell,Sheet sheet)
throws Exception{
int firstC = 0;
int lastC = 0;
int firstR = 0;
int lastR = 0;
String cellValue = null;
for(CellRangeAddress ca:listCombineCell)
{
//获得合并单元格的起始行, 结束行, 起始列, 结束列
firstC = ca.getFirstColumn();
lastC = ca.getLastColumn();
firstR = ca.getFirstRow();
lastR = ca.getLastRow();
if(cell.getRowIndex() >= firstR && cell.getRowIndex() <= lastR)
{
if(cell.getColumnIndex() >= firstC && cell.getColumnIndex() <= lastC)
{
Row fRow = sheet.getRow(firstR);
Cell fCell = fRow.getCell(firstC);
cellValue = getCellValue(fCell);
break;
}
}
else
{
cellValue = "";
}
}
return cellValue;
}

/**
* 获取合并单元格的值
* @param sheet
* @param row
* @param column
* @return
*/
public String getMergedRegionValue(Sheet sheet ,int row , int column){
int sheetMergeCount = sheet.getNumMergedRegions();

for(int i = 0 ; i < sheetMergeCount ; i++){
CellRangeAddress ca = sheet.getMergedRegion(i);
int firstColumn = ca.getFirstColumn();
int lastColumn = ca.getLastColumn();
int firstRow = ca.getFirstRow();
int lastRow = ca.getLastRow();

if(row >= firstRow && row <= lastRow){
if(column >= firstColumn && column <= lastColumn){
Row fRow = sheet.getRow(firstRow);
Cell fCell = fRow.getCell(firstColumn);
return getCellValue(fCell) ;
}
}
}

return null ;
}


/**
* 判断指定的单元格是否是合并单元格
* @param sheet
* @param row 行下标
* @param column 列下标
* @return
*/
private boolean isMergedRegion(Sheet sheet,int row ,int column) {
int sheetMergeCount = sheet.getNumMergedRegions();
for (int i = 0; i < sheetMergeCount; i++) {
CellRangeAddress range = sheet.getMergedRegion(i);
int firstColumn = range.getFirstColumn();
int lastColumn = range.getLastColumn();
int firstRow = range.getFirstRow();
int lastRow = range.getLastRow();
if(row >= firstRow && row <= lastRow){
if(column >= firstColumn && column <= lastColumn){
return true;
}
}
}
return false;
}

private String generateRecordNo(Date recordDate) {
String yearMonth = DateTool.ConvertDateString(recordDate,"yyyyMM");
// YYYYMM01,递增,每月重置末两位
String sql = "FROM ProjectRecord as pr where date_format(pr.recordDate,‘%Y%m‘) = :recordDate";
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("recordDate",yearMonth);
List<ProjectRecord> list = jpqlQuery().setJpql(sql).setParam(paramMap).list();
String recordNo = yearMonth;
if(list.size() > 0 && list.get(0) != null) {
if(list.size() < 9){
recordNo += "0" + (list.size() + 1);
}else {
recordNo += (list.size() + 1);
}
return recordNo;
}
// 生成本月的号
recordNo += "01";
return recordNo;
}

}

poi

标签:返回   service   except   get   failure   scom   +=   list   .class   

原文地址:https://www.cnblogs.com/rain-in-summer/p/8432488.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!