Commit 6a0c77b8 authored by chase's avatar chase

优化报表上传下载

parent 0fe565df
...@@ -87,6 +87,64 @@ public class POIUtil { ...@@ -87,6 +87,64 @@ public class POIUtil {
} }
} }
public static void cloneSheetAndStyle(Sheet sheet, Sheet targetSheet,Workbook tWorkbook) {
for (int r = sheet.getFirstRowNum(); r <= sheet.getLastRowNum(); r++) {
Row row = sheet.getRow(r);
if (null == row) {
continue;
}
Row targetRow = targetSheet.createRow(r);
for (int c = row.getFirstCellNum(); c <= row.getLastCellNum(); c++) {
if(c < 0 ){
continue;
}
Cell cell = row.getCell(c);
if (null == cell) {
continue;
}
Cell targetCell = targetRow.createCell(c);
targetCell.setCellType(cell.getCellTypeEnum());
switch (cell.getCellTypeEnum()) {
case STRING:
if (cell.getStringCellValue().indexOf("KeyIn")>0){
targetCell.setCellValue("");
}else{
targetCell.setCellValue(cell.getStringCellValue());
}
break;
case NUMERIC:
targetCell.setCellValue(cell.getNumericCellValue());
break;
case BOOLEAN:
targetCell.setCellValue(cell.getBooleanCellValue());
break;
case FORMULA:
targetCell.setCellFormula(cell.getCellFormula());
break;
// case ERROR:
//// case BLANK:
//// case _NONE:
default:
break;
}
if (null != cell.getCellComment()) {
targetCell.setCellComment(cell.getCellComment());
}
if (null != cell.getCellStyle()) {
CellStyle newstyle=tWorkbook.createCellStyle();
targetCell.setCellStyle(newstyle);
try{
targetCell.getCellStyle().cloneStyleFrom(cell.getCellStyle());
}catch (Exception e){
//e.printStackTrace();
}
}
if (null != cell.getHyperlink()) {
targetCell.setHyperlink(cell.getHyperlink());
}
}
}
}
public static String getCellFormulaString(Cell cell) { public static String getCellFormulaString(Cell cell) {
switch (cell.getCellTypeEnum()) { switch (cell.getCellTypeEnum()) {
case STRING: case STRING:
......
package pwc.taxtech.atms.controller; package pwc.taxtech.atms.controller;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import pwc.taxtech.atms.common.message.ErrorMessage;
import pwc.taxtech.atms.constant.enums.EnumServiceType; import pwc.taxtech.atms.constant.enums.EnumServiceType;
import pwc.taxtech.atms.dao.OrganizationMapper; import pwc.taxtech.atms.dao.OrganizationMapper;
import pwc.taxtech.atms.dao.ProjectMapper; import pwc.taxtech.atms.dao.ProjectMapper;
import pwc.taxtech.atms.dpo.ReportDto; import pwc.taxtech.atms.dpo.ReportDto;
import pwc.taxtech.atms.dto.*; import pwc.taxtech.atms.dto.*;
import pwc.taxtech.atms.dto.periodReport.PeriodReportDataParam;
import pwc.taxtech.atms.dto.vatdto.*; import pwc.taxtech.atms.dto.vatdto.*;
import pwc.taxtech.atms.entity.OrganizationExample; import pwc.taxtech.atms.entity.OrganizationExample;
import pwc.taxtech.atms.entity.Project; import pwc.taxtech.atms.entity.Project;
import pwc.taxtech.atms.entity.ProjectExample; import pwc.taxtech.atms.entity.ProjectExample;
import pwc.taxtech.atms.service.impl.DataImportService; import pwc.taxtech.atms.service.impl.DataImportService;
import pwc.taxtech.atms.service.impl.ReportUploadService;
import pwc.taxtech.atms.vat.entity.*; import pwc.taxtech.atms.vat.entity.*;
import pwc.taxtech.atms.vat.service.impl.ReportServiceImpl; import pwc.taxtech.atms.vat.service.impl.ReportServiceImpl;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Optional; import java.util.Optional;
@RestController @RestController
...@@ -28,7 +34,8 @@ import java.util.Optional; ...@@ -28,7 +34,8 @@ import java.util.Optional;
public class ReportController { public class ReportController {
@Autowired @Autowired
ReportServiceImpl reportService; ReportServiceImpl reportService;
@Autowired
ReportUploadService reportUploadService;
@RequestMapping(value = "export", method = RequestMethod.POST) @RequestMapping(value = "export", method = RequestMethod.POST)
public ResponseEntity getExportFile(@RequestBody ReportExportDto report) { public ResponseEntity getExportFile(@RequestBody ReportExportDto report) {
return ResponseEntity.ok(reportService.export(report.getReportData(), "~")); return ResponseEntity.ok(reportService.export(report.getReportData(), "~"));
...@@ -51,6 +58,63 @@ public class ReportController { ...@@ -51,6 +58,63 @@ public class ReportController {
return ResponseEntity.ok(reportService.generateData(projectId, EnumServiceType.VAT, mergeManual, period, null, generator)); return ResponseEntity.ok(reportService.generateData(projectId, EnumServiceType.VAT, mergeManual, period, null, generator));
} }
@RequestMapping(value = "exportReportData/{projectId}/{period}", method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public void exportReportData(HttpServletResponse response, @RequestBody PeriodReportDataParam param,
@PathVariable(name = "period", required = false) Integer period,
@PathVariable(name = "projectId", required = false) String projectId) {
OutputStream ouputStream = null;
try {
Workbook tWorkbook = reportService.generateReportData(param.getReportIds(),projectId,period);
response.setContentType("multipart/form-data");
// response.setHeader("Content-Disposition", "attachment;fileName=" + new String(param.getFileName().getBytes("GB2312"), "ISO-8859-1"));
ouputStream = response.getOutputStream();
tWorkbook.write(ouputStream);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(ouputStream!=null){
ouputStream.close();
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
@RequestMapping(value = "uploadReportData/{projectId}/{period}", method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public OperationResultDto uploadReportData(@RequestBody PeriodReportDataParam param,
@PathVariable(name = "period", required = false) Integer period,
@PathVariable(name = "projectId", required = false) String projectId) {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
try {
Workbook tWorkbook = reportService.generateReportData(param.getReportIds(),projectId,period);
tWorkbook.write(bout);
ReportUpload data = new ReportUpload();
data.setProjectId(projectId);
data.setPeriod(period);
reportUploadService.saveData(bout.toByteArray(), data);
return OperationResultDto.success();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(bout!=null){
bout.close();
}
}catch (Exception e) {
e.printStackTrace();
}
}
return OperationResultDto.error(ErrorMessage.SystemError);
}
@RequestMapping(value = "getRunningJob/{projectId}/{period}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @RequestMapping(value = "getRunningJob/{projectId}/{period}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody @ResponseBody
public PeriodJobDto getRunningJob(@PathVariable String projectId, @PathVariable Integer period) { public PeriodJobDto getRunningJob(@PathVariable String projectId, @PathVariable Integer period) {
......
package pwc.taxtech.atms.dto.periodReport;
import java.io.Serializable;
import java.util.List;
public class PeriodReportDataParam implements Serializable {
private static final long serialVersionUID = -2938874414934072910L;
private List<Long> reportIds;
private String fileName;
public List<Long> getReportIds() {
return reportIds;
}
public void setReportIds(List<Long> reportIds) {
this.reportIds = reportIds;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
...@@ -105,4 +105,36 @@ public class ReportUploadService extends BaseService { ...@@ -105,4 +105,36 @@ public class ReportUploadService extends BaseService {
reportUploadMapper.insert(data); reportUploadMapper.insert(data);
} }
public void saveData(byte[] bytes, ReportUpload data) {
String uid = authUserHelper.getCurrentUserId();
User user = userMapper.selectByPrimaryKey(uid);
data.setCreator(user.getUserName());
String fileName = "";
Project project = projectMapper.selectByPrimaryKey(data.getProjectId());
data.setOrgId(project.getOrganizationId());
String period = ""+project.getYear()+(data.getPeriod()>9?data.getPeriod():("0"+data.getPeriod()));
data.setPeriod(Integer.valueOf(period));
fileName += project.getName();
fileName += "-";
fileName += data.getPeriod();
fileName += "-V";
ReportUploadExample example = new ReportUploadExample();
example.createCriteria().andProjectIdEqualTo(data.getProjectId()).andPeriodEqualTo(data.getPeriod());
example.setOrderByClause("version desc");
List<ReportUpload> dataList = reportUploadMapper.selectByExample(example);
if (CollectionUtils.isNotEmpty(dataList)) {
fileName += (dataList.get(0).getVersion() + 1);
data.setVersion(dataList.get(0).getVersion() + 1);
} else {
fileName += 1;
data.setVersion(1);
}
fileName += ".xlsx";
data.setReportName(fileName);
FileUpload fileUpload = didiFileUploadService.uploadFile(bytes, fileName, FileUploadEnum.BizSource.REPORT_UPLOAD.name());
data.setFileUploadId(fileUpload.getUid());
data.setUid(CommonUtils.getUUID());
data.setCreateTime(new Date());
reportUploadMapper.insert(data);
}
} }
...@@ -20,6 +20,7 @@ import pwc.taxtech.atms.common.POIUtil; ...@@ -20,6 +20,7 @@ import pwc.taxtech.atms.common.POIUtil;
import pwc.taxtech.atms.common.util.SpringContextUtil; import pwc.taxtech.atms.common.util.SpringContextUtil;
import pwc.taxtech.atms.constant.enums.CellDataSourceType; import pwc.taxtech.atms.constant.enums.CellDataSourceType;
import pwc.taxtech.atms.dao.ProjectMapper; import pwc.taxtech.atms.dao.ProjectMapper;
import pwc.taxtech.atms.dpo.AnalysisSalesValueDto;
import pwc.taxtech.atms.dto.didiFileUpload.DidiFileIUploadParam; import pwc.taxtech.atms.dto.didiFileUpload.DidiFileIUploadParam;
import pwc.taxtech.atms.dto.didiFileUpload.DidiFileUploadDetailResult; import pwc.taxtech.atms.dto.didiFileUpload.DidiFileUploadDetailResult;
import pwc.taxtech.atms.dto.vatdto.CellCalcInfoDto; import pwc.taxtech.atms.dto.vatdto.CellCalcInfoDto;
...@@ -520,7 +521,70 @@ public class ReportGeneratorImpl { ...@@ -520,7 +521,70 @@ public class ReportGeneratorImpl {
throw Exceptions.SERVER_ERROR_EXCEPTION; throw Exceptions.SERVER_ERROR_EXCEPTION;
} }
} }
public Workbook createWorkBookByPeriodTemplate(List<PeriodTemplate> templates) {
{
Workbook workbook = new XSSFWorkbook();
try {
String filePath = this.getClass().getResource("").toURI().getPath();
String tempPath = filePath.substring(0, filePath.indexOf("classes") + "\\classes".length());
templates.forEach(a -> {
Workbook tWorkbook = null;
File file = null;
if (a.getIsSystemType()) {
file = new File(tempPath + a.getPath());
try {
tWorkbook = WorkbookFactory.create(file);
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
}
} else {
InputStream is = null;
try {
String path = "";
if (a.getPath().indexOf("/") > 0) {
path = a.getPath();
} else {
DidiFileIUploadParam fileParam = new DidiFileIUploadParam();
fileParam.setUuids(Arrays.asList(a.getPath()));
PageInfo<DidiFileUploadDetailResult> uploadDetail = didiFileUploadService.queryPage(fileParam);
Map<String, String> urlMap = null;
if (CollectionUtils.isNotEmpty(uploadDetail.getList())) {
path = uploadDetail.getList().get(0).getViewHttpUrl();
}
}
is = httpFileService.getUserTemplate(path);
tWorkbook = WorkbookFactory.create(is);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//处理workbook
List<AnalysisSalesValueDto> dataList = periodCellDataMapper.selectReportData(a.getTemplateId(),a.getProjectId(),a.getPeriod());
for(AnalysisSalesValueDto cellData:dataList){
Sheet sheet = tWorkbook.getSheetAt(0);
sheet.getRow(cellData.getRowIndex()).getCell(cellData.getColumnIndex()).setCellValue(cellData.getData());
}
POIUtil.cloneSheetAndStyle(tWorkbook.getSheetAt(0), workbook.createSheet(a.getCode()),workbook);
});
return workbook;
} catch (Exception e) {
logger.error("createWorkBookByPeriodTemplate error.", e);
throw Exceptions.SERVER_ERROR_EXCEPTION;
}
}
}
/** /**
* 注册所有的自定义方法到工作簿 * 注册所有的自定义方法到工作簿
......
...@@ -898,7 +898,7 @@ public class ReportServiceImpl extends BaseService { ...@@ -898,7 +898,7 @@ public class ReportServiceImpl extends BaseService {
Iterator<Map.Entry<Integer, List<String>>> iterator = sumMap.entrySet().iterator(); Iterator<Map.Entry<Integer, List<String>>> iterator = sumMap.entrySet().iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
Map.Entry<Integer, List<String>> entry = iterator.next(); Map.Entry<Integer, List<String>> entry = iterator.next();
String sumStr = "Sum("; String sumStr = "PSUM(";
for (String cellNum : entry.getValue()) { for (String cellNum : entry.getValue()) {
sumStr += cellNum + ","; sumStr += cellNum + ",";
} }
...@@ -909,7 +909,32 @@ public class ReportServiceImpl extends BaseService { ...@@ -909,7 +909,32 @@ public class ReportServiceImpl extends BaseService {
} }
} }
public Workbook generateReportData(List<Long> reportIds,String projectId,Integer period){
PeriodReportExample reportExample = new PeriodReportExample();
reportExample.createCriteria().andIdIn(reportIds);
List<PeriodReport> reports = periodReportMapper.selectByExample(reportExample);
PeriodTemplateExample example = new PeriodTemplateExample();
example.createCriteria().andTemplateIdIn(reports.stream().map(m -> m.getTemplateId()).collect(Collectors.toList())).andProjectIdEqualTo(projectId).andPeriodEqualTo(period);
List<PeriodTemplate> dataList = periodTemplateMapper.selectByExample(example);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
Workbook tWorkbook = null;
try {
tWorkbook = reportGenerator.createWorkBookByPeriodTemplate(dataList);
tWorkbook.write(bout);
// FileUpload fileUpload = didiFileUploadService.uploadFile(bout.toByteArray(), "demo.xlsx", FileUploadEnum.BizSource.PERIOD_REPORT_TEMPLATE_UPLOAD.name());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return tWorkbook;
};
public OperationResultDto generateData(String projectId, EnumServiceType serviceType, Boolean isMergeManualData, public OperationResultDto generateData(String projectId, EnumServiceType serviceType, Boolean isMergeManualData,
Integer periodParam, Integer reportType, Optional<String> generator) { Integer periodParam, Integer reportType, Optional<String> generator) {
OperationResultDto operationResultDto = new OperationResultDto(); OperationResultDto operationResultDto = new OperationResultDto();
......
...@@ -118,7 +118,7 @@ public class BB extends FunctionBase implements FreeRefFunction { ...@@ -118,7 +118,7 @@ public class BB extends FunctionBase implements FreeRefFunction {
cellData = agent.getCellData(cellTemplateData.getReportTemplateId(), cellData = agent.getCellData(cellTemplateData.getReportTemplateId(),
cellTemplateData.getCellTemplateId(), curPeriod.getCurPeriod(), project==null?formulaContext.getProjectId():project.getId()); cellTemplateData.getCellTemplateId(), curPeriod.getCurPeriod(), project==null?formulaContext.getProjectId():project.getId());
List<PeriodDataSource> dss = agent.queryManualDataSource(Long.parseLong(cellTemplateData.getCellTemplateId()), List<PeriodDataSource> dss = agent.queryManualDataSource(Long.parseLong(cellTemplateData.getCellTemplateId()),
project==null?formulaContext.getProjectId():project.getId(), bo.getPeriod()); project==null?formulaContext.getProjectId():project.getId(), curPeriod.getCurPeriod());
nullCellDto.extractFromGroup(bo, curPeriod, cellData, cellTemplateData); nullCellDto.extractFromGroup(bo, curPeriod, cellData, cellTemplateData);
if (cellData.getData() == null && !dss.isEmpty()) { if (cellData.getData() == null && !dss.isEmpty()) {
cellValue = dss.get(0).getAmount(); cellValue = dss.get(0).getAmount();
......
package pwc.taxtech.atms.vat.dao; package pwc.taxtech.atms.vat.dao;
import java.util.List;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.session.RowBounds;
...@@ -9,6 +8,8 @@ import pwc.taxtech.atms.dpo.AnalysisSalesValueDto; ...@@ -9,6 +8,8 @@ import pwc.taxtech.atms.dpo.AnalysisSalesValueDto;
import pwc.taxtech.atms.vat.entity.PeriodCellData; import pwc.taxtech.atms.vat.entity.PeriodCellData;
import pwc.taxtech.atms.vat.entity.PeriodCellDataExample; import pwc.taxtech.atms.vat.entity.PeriodCellDataExample;
import java.util.List;
@Mapper @Mapper
public interface PeriodCellDataMapper extends MyVatMapper { public interface PeriodCellDataMapper extends MyVatMapper {
/** /**
...@@ -112,4 +113,8 @@ public interface PeriodCellDataMapper extends MyVatMapper { ...@@ -112,4 +113,8 @@ public interface PeriodCellDataMapper extends MyVatMapper {
List<PeriodCellData> selectDataByCellTemplateIdAround(@Param("bufferString") String bufferString); List<PeriodCellData> selectDataByCellTemplateIdAround(@Param("bufferString") String bufferString);
List<AnalysisSalesValueDto> selectAnalysisSalesValueDto(@Param("reportId")String reportId, @Param("projectId")String projectId); List<AnalysisSalesValueDto> selectAnalysisSalesValueDto(@Param("reportId")String reportId, @Param("projectId")String projectId);
List<AnalysisSalesValueDto> selectReportData(@Param("reportId") Long reportId,
@Param("projectId") String projectId,
@Param("period") Integer period);
} }
\ No newline at end of file
...@@ -110,4 +110,31 @@ ...@@ -110,4 +110,31 @@
pcd.report_id = #{reportId} and pcd.report_id = #{reportId} and
pcd.project_id = #{projectId} pcd.project_id = #{projectId}
</select> </select>
<select id = "selectReportData" resultType="pwc.taxtech.atms.dpo.AnalysisSalesValueDto">
select cell_template.row_index as rowIndex,
cell_template.column_index as columnIndex,
concat(CONVERT(cell_data.data, decimal(12, 6)) + if(data_source.amount is null, 0, data_source.amount)) as data
from period_cell_data cell_data
left join period_cell_template cell_template
on cell_data.cell_template_id = cell_template.cell_template_id
and
cell_data.project_id = cell_template.project_id
and
cell_data.period = cell_template.period
left join period_data_source data_source
on
data_source.type = 10
and
cell_data.project_id = data_source.project_id
and
cell_data.period = data_source.period
and
cell_data.cell_template_id = data_source.cell_template_id
where
cell_data.project_id = #{projectId}
and cell_data.period = #{period}
and cell_template.project_id = #{projectId}
and cell_template.period = #{period}
and cell_template.report_template_id = #{reportId}
</select>
</mapper> </mapper>
\ No newline at end of file
commonModule.controller('VatReportViewController', ['$scope', '$rootScope', '$log', '$translate', '$timeout', '$q', '$compile', '$state', '$stateParams', commonModule.controller('VatReportViewController', ['$scope', '$rootScope', '$log', '$translate', '$timeout', '$q', '$compile', '$state', '$stateParams',
'apiInterceptor', 'vatExportService', 'SweetAlert', 'BSPLService', 'vatReportService', 'vatReportCacheService', 'vatSessionService', 'apiInterceptor', 'vatExportService', 'SweetAlert', 'BSPLService', 'vatReportService', 'vatReportCacheService', 'vatSessionService',
'loginContext', 'enums', 'vatCommonService', 'vatWorkflowService', 'projectService', '$uibModal', '$cookies', 'Upload', 'vatImportService', 'vatApproveService', 'loginContext', 'enums', 'vatCommonService', 'vatWorkflowService', 'projectService', '$uibModal', '$cookies', 'Upload', 'vatImportService', 'vatApproveService', '$http', 'apiConfig',
function ($scope, $rootScope, $log, $translate, $timeout, $q, $compile, $state, $stateParams, apiInterceptor, vatExportService, SweetAlert, BSPLService, function ($scope, $rootScope, $log, $translate, $timeout, $q, $compile, $state, $stateParams, apiInterceptor, vatExportService, SweetAlert, BSPLService,
vatReportService, vatReportCacheService, vatSessionService, loginContext, enums, vatCommonService, vatWorkflowService, projectService, vatReportService, vatReportCacheService, vatSessionService, loginContext, enums, vatCommonService, vatWorkflowService, projectService,
$uibModal, $cookies, Upload, vatImportService, vatApproveService) { $uibModal, $cookies, Upload, vatImportService, vatApproveService, $http, apiConfig) {
'use strict'; 'use strict';
$log.debug('VatReportViewController.ctor()...'); $log.debug('VatReportViewController.ctor()...');
...@@ -623,8 +623,8 @@ ...@@ -623,8 +623,8 @@
// if (element.items.length === 1) { // if (element.items.length === 1) {
// outItems = JSON.parse(element.items[0]); // outItems = JSON.parse(element.items[0]);
// } else { // } else {
outItems = element.items; outItems = element.items;
convert = true; convert = true;
// } // }
//todo: according to element to get the detail data //todo: according to element to get the detail data
...@@ -971,7 +971,49 @@ ...@@ -971,7 +971,49 @@
SweetAlert.warning($translate.instant('ExportReportRequiredCheck')); SweetAlert.warning($translate.instant('ExportReportRequiredCheck'));
return; return;
} }
$('#busy-indicator-container').show();
var reportIds = [];
angular.forEach($scope.selectedReportIds, function (reportId) {
var node = _.first(_.where(grp.children, {reportId: reportId}));
if (node) {
reportIds.push(node.reportId);
}
})
if ('export' == $scope.evenType) {
var xhr = new XMLHttpRequest();
xhr.onload = function (e) {
var arraybuffer = xhr.response;
exportToExcel(arraybuffer, vatSessionService.project.name + '-' + vatSessionService.month + '-纳税申报.xlsx');
$('#busy-indicator-container').hide();
};
xhr.open("POST", apiInterceptor.webApiHostUrl + '/Report/exportReportData/' + vatSessionService.project.id + '/' + vatSessionService.month, true);
xhr.setRequestHeader("Authorization", apiInterceptor.tokenType + ' ' + apiInterceptor.apiToken());
xhr.setRequestHeader("Content-Type", 'application/json;charset=UTF-8');
xhr.responseType = "arraybuffer";
xhr.send(JSON.stringify({
reportIds: reportIds
}));
return;
}
if ('upload' == $scope.evenType) {
var xhr = new XMLHttpRequest();
xhr.onload = function (e) {
if(xhr.status === 200){
SweetAlert.success('', $translate.instant('FileUploadSuccess'));
}else{
SweetAlert.success('', $translate.instant('FileUploadFailed'));
}
$('#busy-indicator-container').hide();
};
xhr.open("POST", apiInterceptor.webApiHostUrl + '/Report/uploadReportData/' + vatSessionService.project.id + '/' + vatSessionService.month, true);
xhr.setRequestHeader("Authorization", apiInterceptor.tokenType + ' ' + apiInterceptor.apiToken());
xhr.setRequestHeader("Content-Type", 'application/json;charset=UTF-8');
xhr.responseType = "arraybuffer";
xhr.send(JSON.stringify({
reportIds: reportIds
}));
return;
}
//设置报表的排序号,用于对导出的报表sheet进行排序 //设置报表的排序号,用于对导出的报表sheet进行排序
var orderIndex = 0; var orderIndex = 0;
_.each(grp.children, function (item) { _.each(grp.children, function (item) {
...@@ -1034,6 +1076,104 @@ ...@@ -1034,6 +1076,104 @@
return; return;
}; };
var exportToExcel = function (data, filename) {
var defer = $q.defer();
// var octetStreamMime = 'application/vnd.ms-excel';
var success = false;
// Get the headers
// headers = headers();
// Get the filename from the x-filename header or default to "download.bin"
// var filename = decodeURI(headers['x-file-name']) + defaultFileName;
// Determine the content type from the header or default to "application/octet-stream"
// var contentType = headers['content-type'] || octetStreamMime;
try {
// Try using msSaveBlob if supported
//console.log("Trying saveBlob method ...");
var blob = new Blob([data], {type: "arraybuffer"});
if (navigator.msSaveBlob)
navigator.msSaveBlob(blob, filename);
else {
// Try using other saveBlob implementations, if available
var saveBlob = navigator.webkitSaveBlob || navigator.mozSaveBlob || navigator.saveBlob;
if (saveBlob === undefined) throw "Not supported";
saveBlob(blob, filename);
}
//console.log("saveBlob succeeded");
success = true;
} catch (ex) {
$log.debug("saveBlob method failed with the following exception:");
$log.debug(ex);
}
if (!success) {
// Get the blob url creator
var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;
if (urlCreator) {
// Try to use a download link
var link = document.createElement('a');
if ('download' in link) {
// Try to simulate a click
try {
// Prepare a blob URL
//console.log("Trying download link method with simulated click ...");
var blobdownload = new Blob([data], {type: "arraybuffer"});
var urldownload = urlCreator.createObjectURL(blobdownload);
link.setAttribute('href', urldownload);
// Set the download attribute (Supported in Chrome 14+ / Firefox 20+)
link.setAttribute("download", filename);
// Simulate clicking the download link
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
link.dispatchEvent(event);
//console.log("Download link method with simulated click succeeded");
success = true;
} catch (ex) {
$log.debug("Download link method with simulated click failed with the following exception:");
$log.debug(ex);
$q.reject();
}
}
if (!success) {
// Fallback to window.location method
try {
// Prepare a blob URL
// Use application/octet-stream when using window.location to force download
//console.log("Trying download link method with window.location ...");
var blobsuccess = new Blob([data], {type: "arraybuffer"});
var urlsuccess = urlCreator.createObjectURL(blobsuccess);
window.location = urlsuccess;
//console.log("Download link method with window.location succeeded");
success = true;
} catch (ex) {
//console.log("Download link method with window.location failed with the following exception:");
$log.debug(ex);
$q.reject();
}
}
}
}
if (!success) {
// Fallback to window.open method
$log.debug("No methods worked for saving the arraybuffer, using last resort window.open");
window.open(httpPath, '_blank', '');
}
//Delete the file
// deleteFile(encodeURI(filename));
defer.resolve('success');
return defer.promise;
};
var timeOutCount = 0; var timeOutCount = 0;
function timeOutExportSpread(exportReportData) { function timeOutExportSpread(exportReportData) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment