excel联调完毕

web_backend_develope
chenlw 9 years ago
parent cbb42e1a3d
commit fa3522b71d

@ -63,17 +63,17 @@ PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
</resultMap> </resultMap>
<sql id="conditionsFilters"> <sql id="conditionsFilters">
<if test="cityName!=null"> <if test="cityName!=null">
AND pre_data_details.city_name=#{cityName} AND standard_data_details.city_name=#{cityName}
</if> </if>
<if test="districtName!=null"> <if test="districtName!=null">
AND AND
pre_data_details.district_name=#{districtName} standard_data_details.district_name=#{districtName}
</if> </if>
<if test="dataVersion !=null"> <if test="dataVersion !=null">
AND pre_data_details.data_version=#{dataVersion} AND standard_data_details.data_version=#{dataVersion}
</if> </if>
<if test="systemName !=null"> <if test="systemName !=null">
AND pre_data_details.system_name=#{systemName} AND standard_data_details.system_name=#{systemName}
</if> </if>
<if test="array !=null and array.length > 0"> <if test="array !=null and array.length > 0">
<foreach collection="array" item="item" index="index"> <foreach collection="array" item="item" index="index">
@ -84,7 +84,7 @@ PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
<!-- sql txt Base_Column_List --> <!-- sql txt Base_Column_List -->
<sql id="Base_Column_List"> <sql id="Base_Column_List">
area_code,city_name,district_name,system_name,area_level,data_version,begin_in_use,function_details, id,area_code,city_name,district_name,system_name,area_level,data_version,begin_in_use,function_details,
department_manager,manager_contacts,sys_developer_full_name,data_base_type,data_base_version, department_manager,manager_contacts,sys_developer_full_name,data_base_type,data_base_version,
is_budget_exec,is_budget_quota,is_collection,is_department_budget,total_budget_account, is_budget_exec,is_budget_quota,is_collection,is_department_budget,total_budget_account,
final_account_manage,report_form_manage,non_tax_revenue_manage,wage_system, final_account_manage,report_form_manage,non_tax_revenue_manage,wage_system,
@ -96,20 +96,20 @@ PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
resultMap="getEntityByText"> resultMap="getEntityByText">
SELECT SELECT
<include refid="Base_Column_List" /> <include refid="Base_Column_List" />
FROM pre_data_details FROM standard_data_details
<where> <where>
<include refid="conditionsFilters" /> <include refid="conditionsFilters" />
<choose> <choose>
<when test="offset > 0"> <when test="offset > 0">
and pre_data_details.id>= #{offset} and standard_data_details.id>= #{offset}
</when> </when>
<otherwise> <otherwise>
and pre_data_details.id>=0 and standard_data_details.id>=0
</otherwise> </otherwise>
</choose> </choose>
</where> </where>
ORDER BY pre_data_details.area_code,pre_data_details.sys_code ORDER BY standard_data_details.area_code,standard_data_details.sys_code
<if test="limit > 0"> <if test="limit > 0">
LIMIT #{limit} LIMIT #{limit}
</if> </if>
@ -121,7 +121,7 @@ PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
<!-- 获取数据符合筛选条件的总记录条数 --> <!-- 获取数据符合筛选条件的总记录条数 -->
<select id="getLimitedDataCount" resultType="java.lang.Integer" <select id="getLimitedDataCount" resultType="java.lang.Integer"
parameterType="com.platform.entities.PagerOptions"> parameterType="com.platform.entities.PagerOptions">
SELECT COUNT(id) FROM pre_data_details SELECT COUNT(id) FROM standard_data_details
<where> <where>
<include refid="conditionsFilters" /> <include refid="conditionsFilters" />
</where> </where>
@ -131,12 +131,12 @@ PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
<!-- 获取数据查询的起始di --> <!-- 获取数据查询的起始di -->
<select id="getLimitedBeginId" resultType="java.lang.Integer" <select id="getLimitedBeginId" resultType="java.lang.Integer"
parameterType="com.platform.entities.PagerOptions"> parameterType="com.platform.entities.PagerOptions">
SELECT MAX(idx) FROM (SELECT id idx FROM pre_data_details SELECT MAX(idx) FROM (SELECT id idx FROM standard_data_details
ORDER BY id LIMIT 0,#{totalLimit}) AS TEMP ORDER BY id LIMIT 0,#{totalLimit}) AS TEMP
</select> </select>
<select id="getIdIsExist" parameterType="java.util.List" resultType="java.lang.String"> <select id="getIdIsExist" parameterType="java.util.List" resultType="java.lang.String">
select data_path select data_path
from pre_data_details from standard_data_details
where id in where id in
<foreach item="item" index="index" collection="list" open="(" separator="," close=")"> <foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item} #{item}
@ -155,13 +155,13 @@ PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
<select id="findAll" resultMap="getEntityByText"> <select id="findAll" resultMap="getEntityByText">
SELECT SELECT
<include refid="Base_Column_List" /> <include refid="Base_Column_List" />
FROM pre_data_details FROM standard_data_details
ORDER BY pre_data_details.area_code,pre_data_details.sys_code ORDER BY standard_data_details.area_code,standard_data_details.sys_code
</select> </select>
<!-- 批量插入 --> <!-- 批量插入 -->
<select id="insertBatch" parameterType="java.util.List"> <select id="insertBatch" parameterType="java.util.List">
INSERT INTO pre_data_info ( <include refid="Batch_Column_List" /> ) INSERT INTO standard_data_info ( <include refid="Batch_Column_List" /> )
VALUES VALUES
<foreach collection="list" item="item" index="index" separator=","> <foreach collection="list" item="item" index="index" separator=",">
(#{item.areaCode,jdbcType=VARCHAR},#{item.sysCode,jdbcType=INTEGER},#{item.areaLevel,jdbcType=VARCHAR},#{item.dataVersion,jdbcType=VARCHAR},#{item.beginUseTime},#{item.functionDetails}, (#{item.areaCode,jdbcType=VARCHAR},#{item.sysCode,jdbcType=INTEGER},#{item.areaLevel,jdbcType=VARCHAR},#{item.dataVersion,jdbcType=VARCHAR},#{item.beginUseTime},#{item.functionDetails},
@ -175,7 +175,7 @@ PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
<!-- 更新字段 --> <!-- 更新字段 -->
<update id="update" parameterType="com.platform.entities.PreDataInfoFull"> <update id="update" parameterType="com.platform.entities.PreDataInfoFull">
UPDATE UPDATE
pre_data_info standard_data_info
<set> <set>
<trim suffixOverrides=","> <trim suffixOverrides=",">
<if test="collection != null and collection != ''"> <if test="collection != null and collection != ''">
@ -253,7 +253,7 @@ PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
<select id="getAreaSysNameExistByAreaSysName" parameterType="java.util.List" resultType="java.lang.String"> <select id="getAreaSysNameExistByAreaSysName" parameterType="java.util.List" resultType="java.lang.String">
SELECT SELECT
CONCAT(area_code,',',system_name) CONCAT(area_code,',',system_name)
FROM pre_data_details FROM standard_data_details
where where
CONCAT(area_code,',',system_name) IN CONCAT(area_code,',',system_name) IN
<foreach item="item" index="index" collection="list" open="(" separator="," close=")"> <foreach item="item" index="index" collection="list" open="(" separator="," close=")">

@ -122,7 +122,10 @@ public class ExcelController extends BaseController{
// 文件下载处理函数 // 文件下载处理函数
@RequestMapping(value = "/file/download") @RequestMapping(value = "/file/download")
public ResponseEntity<byte[]> download(HttpServletRequest request, public ResponseEntity<byte[]> download(HttpServletRequest request,
HttpServletResponse response) throws IOException { HttpServletResponse response) throws Exception {
//先导出
preDataInfoService.exportExcel(Configs.FILE_DOWNLOAD_PATH);
File file = new File(Configs.FILE_DOWNLOAD_PATH); File file = new File(Configs.FILE_DOWNLOAD_PATH);
System.out.println(Configs.FILE_DOWNLOAD_PATH); System.out.println(Configs.FILE_DOWNLOAD_PATH);
if (file.exists()) { if (file.exists()) {

@ -1,7 +1,12 @@
package com.platform.entities; package com.platform.entities;
import java.util.ArrayList;
import java.util.List;
public class PreDataInfo { public class PreDataInfo {
private int id;
/** 是否更新 */ /** 是否更新 */
private String isupdate = "-"; private String isupdate = "-";
@ -76,6 +81,23 @@ public class PreDataInfo {
/** 政府性债务管理 */ /** 政府性债务管理 */
private String governmentDebtManage; private String governmentDebtManage;
/** 业务范围 */
private List<String> workRange;
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/** /**
* @return the isupdate * @return the isupdate
@ -428,4 +450,50 @@ public class PreDataInfo {
this.governmentDebtManage = governmentDebtManage; this.governmentDebtManage = governmentDebtManage;
} }
/**
* @return the workRange
*/
public List<String> getWorkRange() {
return workRange;
}
/**
* @param workRange the workRange to set
*/
public void setWorkRange(List<String> workRange) {
this.workRange = workRange;
if (null == this.workRange) {
this.workRange = new ArrayList<String>();
}
if ("是".equals(departmentBudgetManage)) {
this.workRange.add("部门预算管理");
}
if ("是".equals(budgetQuotaManage)) {
this.workRange.add("预算指标管理");
}
if ("是".equals(budgetExecManage)) {
this.workRange.add("预算执行管理");
}
if ("是".equals(totalBudgetAccount)) {
this.workRange.add("总预算会计");
}
if ("是".equals(finalAccountManage)) {
this.workRange.add("决算管理");
}
if ("是".equals(reportFormManage)) {
this.workRange.add("报表管理");
}
if ("是".equals(nonTaxManage)) {
this.workRange.add("非税收入管理");
}
if ("是".equals(wageSystem)) {
this.workRange.add("工资统发系统");
}
if ("是".equals(analysisOfFinancialEconomicProsperity)) {
this.workRange.add("财政经济景气预测与分析");
}
if ("是".equals(governmentDebtManage)) {
this.workRange.add("政府性债务管理");
}
}
} }

@ -21,6 +21,13 @@ public interface IPreDataInfoService {
*/ */
public Map<String, List> importExcel(List<String> paths)throws Exception; public Map<String, List> importExcel(List<String> paths)throws Exception;
/**
* @param paths excel
* @return
* @throws Exception
*/
public Map<String, List> exportExcel(String path)throws Exception;
/** /**
* @param op * @param op
* @return * @return

@ -1,6 +1,7 @@
package com.platform.service.impl; package com.platform.service.impl;
import java.io.File; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
@ -14,6 +15,7 @@ import javax.annotation.Resource;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.platform.utils.BeanCopy; import com.platform.utils.BeanCopy;
@ -50,6 +52,9 @@ public class PreDataInfoServiceImpl implements IPreDataInfoService {
@Override @Override
public List<PreDataInfo> findAll() throws Exception { public List<PreDataInfo> findAll() throws Exception {
List<PreDataInfo> result = preDataInfoDao.findAll(); List<PreDataInfo> result = preDataInfoDao.findAll();
for (PreDataInfo preDataInfo : result) {
preDataInfo.setWorkRange(new ArrayList<String>());
}
return result; return result;
} }
@ -94,7 +99,7 @@ public class PreDataInfoServiceImpl implements IPreDataInfoService {
//Excel导入 //Excel导入
try { try {
//excel数据 --> java bean //excel数据 --> java bean
List<PreDataInfo> subPreData = ExcelOperation.readExcel4Update(workbook, Constant.EXCEL_TEMPLATE_INIT_ROW, PreDataInfo.class); List<PreDataInfo> subPreData = ExcelOperation.readExcel4Update(workbook, Constant.EXCEL_TEMPLATE_INIT_ROW, 0, PreDataInfo.class, "id", "workRange");
if (null != subPreData && subPreData.size() > 0) { if (null != subPreData && subPreData.size() > 0) {
//是否是 同一个县区的 系统--是则 加入 //是否是 同一个县区的 系统--是则 加入
boolean isSameArea = true; boolean isSameArea = true;
@ -307,4 +312,39 @@ public class PreDataInfoServiceImpl implements IPreDataInfoService {
return result; return result;
} }
@Override
public Map<String, List> exportExcel(String path) throws Exception {
Map<String, List> map = new HashMap<String, List>();
List<String> errList = new ArrayList<String>();
List<PreDataInfo> list = findAll();
// InputStreamReader in= new InputStreamReader(Resource.class.getResourceAsStream(templateFilePath), "UTF-8");
ClassPathResource res = new ClassPathResource(Constant.SYSTEM_INFO_EXCEL_TEMPLATE_FIEL_PATH);
//此处 耗时太久原因excel 2007 以后采用的方式不同造成的建议升级 到 poi 3.15以上)
XSSFWorkbook workbook = null;
XSSFWorkbook result = null;
try {
workbook = new XSSFWorkbook(res.getInputStream());
result = ExcelOperation.writeExcelTemplate(workbook, Constant.EXCEL_TEMPLATE_INIT_ROW, 0, 25, list, "id", "workRange");
} catch (IllegalArgumentException
| IllegalAccessException | IOException e) {
errList.add(e.getMessage());
}
try {
File f = new File(path);
FileOutputStream fileOut = null;
if (f.exists()) {
fileOut = new FileOutputStream(f);
result.write(fileOut);
fileOut.close();
}
else {
errList.add("without this file "+path);
}
} catch (IOException e) {
errList.add(e.getMessage());
}
map.put("err", errList);
return map;
}
} }

@ -4,6 +4,7 @@ import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCell;
@ -23,17 +24,21 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelOperation { public class ExcelOperation {
/** excel /** excel
* @param templateFilePath * @param workbook
* @param excelInitRow excelInitRow ( Constant.EXCEL_TEMPLATE_INIT_ROW)
* @param excelInitCell excelInitCell
* @param excelEndCell excelEndCell
* @param list list * @param list list
* @param excelInitRow //从第excelInitRow行 开始填充数据,( Constant.EXCEL_TEMPLATE_INIT_ROW) * @param filter list"id"
* @return HSSFWorkbook * @return XSSFWorkbook
* @throws FileNotFoundException * @throws FileNotFoundException
* @throws IOException * @throws IOException
* @throws IllegalArgumentException * @throws IllegalArgumentException
* @throws IllegalAccessException * @throws IllegalAccessException
*///从第几行 填充数据 */
public static XSSFWorkbook writeExcelTemplate(XSSFWorkbook workbook, int excelInitRow, List list) throws FileNotFoundException, IOException, IllegalArgumentException, IllegalAccessException { public static XSSFWorkbook writeExcelTemplate(XSSFWorkbook workbook, int excelInitRow, int excelInitCell, int excelEndCell,List list, String... filter) throws FileNotFoundException, IOException, IllegalArgumentException, IllegalAccessException {
List<String> filters = new ArrayList<String>();
filters.addAll(Arrays.asList(filter));
//读取工作表 //读取工作表
XSSFSheet sheet = workbook.getSheetAt(0);//getSheet("Sheet1"); XSSFSheet sheet = workbook.getSheetAt(0);//getSheet("Sheet1");
XSSFRow row; XSSFRow row;
@ -46,15 +51,30 @@ public class ExcelOperation {
Object obj = list.get(i); Object obj = list.get(i);
Field[] fields = obj.getClass().getDeclaredFields(); Field[] fields = obj.getClass().getDeclaredFields();
lengths = fields.length; lengths = fields.length;
int num = 0;
for (int j = 0; j < lengths; j++) { for (int j = 0; j < lengths; j++) {
fields[j].setAccessible(true); if (j - num >= lengths) {
break;
}
if (j >= excelEndCell) {
break;
}
num = getWriteIndex(filters, fields, j - num, num);
if (num == 1) {
break;
}
Field tmpField = fields[j - num];
tmpField.setAccessible(true);
cell = row.createCell((short) j,HSSFCellStyle.ALIGN_CENTER); cell = row.createCell((short) j,HSSFCellStyle.ALIGN_CENTER);
cell.setCellType(HSSFCell.CELL_TYPE_STRING); cell.setCellType(HSSFCell.CELL_TYPE_STRING);
Object value = fields[j].get(obj); Object value = tmpField.get(obj);
if (null != value) { if (null != value) {
//int型 //int型
if (fields[j].getType().toString().contains("Integer")) { if (tmpField.getType().toString().contains("Integer") || tmpField.getType().toString().contains("int")) {
cell.setCellValue(String.valueOf(value)); if (filters.contains(tmpField.getName()))
cell.setCellValue("-");
else
cell.setCellValue(String.valueOf(value));
} }
else { else {
cell.setCellValue(value.toString()); cell.setCellValue(value.toString());
@ -123,14 +143,18 @@ public class ExcelOperation {
} }
/** excel /** excel
* @param workbook excelXSSFWorkbook * @param workbook excelXSSFWorkbook
* @param excelInitRow * @param excelInitRow
* @param excelInitCell
* @param classz excel * @param classz excel
* @return * @param filter excel
* @throws IllegalAccessException * @return
* @throws InstantiationException * @throws InstantiationException
* @throws IllegalAccessException
*/ */
public static List readExcel4Update(XSSFWorkbook workbook, int excelInitRow, Class<?> classz) throws InstantiationException, IllegalAccessException { public static List readExcel4Update(XSSFWorkbook workbook, int excelInitRow, int excelInitCell, Class<?> classz, String... filter) throws InstantiationException, IllegalAccessException {
List<String> filters = new ArrayList<String>();
filters.addAll(Arrays.asList(filter));
List list = null; List list = null;
//读取工作表 //读取工作表
XSSFSheet sheet = workbook.getSheetAt(0);//getSheet("Sheet1"); XSSFSheet sheet = workbook.getSheetAt(0);//getSheet("Sheet1");
@ -150,38 +174,48 @@ public class ExcelOperation {
for (int i = excelInitRow; i < rowNum; i++) { for (int i = excelInitRow; i < rowNum; i++) {
//获得当前行 //获得当前行
row = sheet.getRow(i); row = sheet.getRow(i);
cell = row.getCell(0); cell = row.getCell(excelInitCell);
if ("-".equals(getValue(cell)) || "".equals(getValue(cell))) { if ("-".equals(getValue(cell))) {
continue; continue;
} }
//实例化 //实例化
Object newObj = classz.newInstance(); Object newObj = classz.newInstance();
Field[] fields = newObj.getClass().getDeclaredFields(); Field[] fields = newObj.getClass().getDeclaredFields();
int fieldSize = fields.length;
boolean isAddObj = false; boolean isAddObj = false;
int num = 0;
//遍历每列的数据 //遍历每列的数据
for (int j = 0; j < objColl; j++) { for (int j = excelInitCell; j < objColl; j++) {
cell = row.getCell(j); cell = row.getCell(j);
if (j + num >= fieldSize) {
break;
}
num = getIndex(filters, fields, j + num, num);
if (num == -1) {
break;
}
Field tmpField = fields[j + num];
if (null != cell) { if (null != cell) {
fields[j].setAccessible(true); tmpField.setAccessible(true);
String cellString = getValue(cell); String cellString = getValue(cell);
if (!"".equals(cellString)) { if (!"".equals(cellString)) {
isAddObj = true; isAddObj = true;
//int型 //int型
if (fields[j].getType().toString().contains("Integer") ||fields[j].getType().toString().contains("int")) { if (tmpField.getType().toString().contains("Integer") ||tmpField.getType().toString().contains("int")) {
double dnum = Double.valueOf(cellString); double dnum = Double.valueOf(cellString);
int inum = (int) dnum; int inum = (int) dnum;
fields[j].set(newObj, inum); tmpField.set(newObj, inum);
} }
//double型 //double型
else if (fields[j].getType().toString().contains("Double") ||fields[j].getType().toString().contains("double")) { else if (tmpField.getType().toString().contains("Double") ||tmpField.getType().toString().contains("double")) {
fields[j].set(newObj, Double.valueOf(cellString)); tmpField.set(newObj, Double.valueOf(cellString));
} }
//boolean型 //boolean型
else if (fields[j].getType().toString().contains("boolean") ||fields[j].getType().toString().contains("Boolean")) { else if (tmpField.getType().toString().contains("boolean") ||tmpField.getType().toString().contains("Boolean")) {
fields[j].set(newObj, Boolean.valueOf(cellString)); tmpField.set(newObj, Boolean.valueOf(cellString));
} }
else { else {
fields[j].set(newObj, cellString); tmpField.set(newObj, cellString);
} }
} }
@ -201,6 +235,9 @@ public class ExcelOperation {
*/ */
private static String getValue(XSSFCell cell) { private static String getValue(XSSFCell cell) {
String value =""; String value ="";
if (null == cell) {
return value;
}
switch (cell.getCellType()) { switch (cell.getCellType()) {
case XSSFCell.CELL_TYPE_NUMERIC: case XSSFCell.CELL_TYPE_NUMERIC:
value = String.valueOf(cell.getNumericCellValue()); value = String.valueOf(cell.getNumericCellValue());
@ -216,4 +253,45 @@ public class ExcelOperation {
} }
return value.trim(); return value.trim();
} }
/** filters
* @param filters
* @param fields
* @param cur
* @param num
* @return
*/
private static int getIndex(List<String> filters, Field[] fields,int cur, int num) {
if (null == filters || filters.size() == 0) {
return num;
}
if (cur >= fields.length) {
return -1;
}
if (filters.contains(fields[cur].getName())) {
num++;
num = getIndex(filters, fields, cur+1, num);
}
return num;
}
/** filters
* @param filters
* @param fields
* @param cur
* @param num
* @return
*/
private static int getWriteIndex(List<String> filters, Field[] fields,int cur, int num) {
if (null == filters || filters.size() == 0) {
return num;
}
if (cur >= fields.length) {
return 1;
}
if (filters.contains(fields[cur].getName())) {
num--;
num = getWriteIndex(filters, fields, cur+1, num);
}
return num;
}
} }

Loading…
Cancel
Save