@RequestMapping("/exportList")
@ResponseBody
public Map<String, Object> exportList(HttpServletRequest request, HttpServletResponse response, HttpSession session,
WarehouseInboundParamVO vo) throws IOException, InvalidFormatException {
vo.setPage(0);
vo.setPageSize(2000);
PageQueryResult<WarehouseInboundVO> list = warehouseInboundService.selectInboundList(vo);
if (list == null) {
System.out.println("导出店铺数据为空,没有查询到数据!!!!");
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("1");
Row row = sheet.createRow((short) 0);
row.createCell(0).setCellValue("没有数据");
row = sheet.createRow(1);
row.createCell(0).setCellValue("没有找到数据 - - !!!!!");
ExcelUtil.downloadExcel(response, wb, "入库记录");
return APIUtil.toMap(HttpStatus.SUCCESS.getValue(), true);
}
List<WarehouseInboundVO> listVo = list.getData();
if (listVo == null || listVo.size() == 0) {
System.out.println("导出店铺数据为空,没有查询到数据!!!!");
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("1");
Row row = sheet.createRow((short) 0);
row.createCell(0).setCellValue("没有数据");
row = sheet.createRow(1);
row.createCell(0).setCellValue("没有找到数据 - - !!!!!");
ExcelUtil.downloadExcel(response, wb, "入库记录");
return APIUtil.toMap(HttpStatus.SUCCESS.getValue(), true);
}
logger.info("finance..记录数:{}", listVo.size()); List<Map<String, Object>> listArr = new ArrayList<>(); for (int i = 0; i < listVo.size(); i++) {
InboundOrder inbound = warehouseInboundService.getInbound(listVo.get(i).getId()); Date createDate = listVo.get(i).getCreateDate();
Calendar calendar = Calendar.getInstance();
calendar.setTime(createDate);
Integer year = calendar.get(Calendar.YEAR);
Integer month = calendar.get(Calendar.MONTH) + 1; // 第一个月从0开始,所以得到月份+1
Integer day = calendar.get(Calendar.DAY_OF_MONTH); List<InboundItem> inboundItems = inbound.getItems();
for (int j = 0; j < inboundItems.size(); j++) {
WarehouseGoods goods = goodsQueryService.getWarehouseGoods(inboundItems.get(j).getItemId());
// 时间
Map<String, Object> map = new HashMap<String, Object>(); map.put("time", year + "/" + month + "/" + day);
map.put("year", year);
map.put("month", month);
map.put("day", day);
if (StringUtil.isEmpty(goods.getItemNum())) {
map.put("itemNum", "-");
} else {
map.put("itemNum", goods.getItemNum());
} map.put("barCode", goods.getBarCode());
if (StringUtil.isEmpty(goods.getCategoryOneName())) {
map.put("categoryOneName", "-");
} else {
map.put("categoryOneName", goods.getCategoryOneName());
}
if (StringUtil.isEmpty(goods.getCategoryTwoName())) {
map.put("categoryTwoName", "-");
} else {
map.put("categoryTwoName", goods.getCategoryTwoName());
} if (StringUtil.isEmpty(goods.getBrandName())) {
map.put("brandName", "-");
} else {
map.put("brandName", goods.getBrandName());
}
if (StringUtil.isEmpty(inboundItems.get(j).getItemName())) {
map.put("itemName", "-");
} else {
map.put("itemName", inboundItems.get(j).getItemName());
}
if (StringUtil.isEmpty(inboundItems.get(j).getSpecification())) {
map.put("specification", "-");
} else {
map.put("specification", inboundItems.get(j).getSpecification());
}
if (StringUtil.isEmpty(goods.getSpecificationName())) {
map.put("specificationName", "-");
} else {
map.put("specificationName", goods.getSpecificationName());
}
if (StringUtil.isEmpty(inbound.getSupplierName())) {
map.put("supplierName", "-");
} else {
map.put("supplierName", inbound.getSupplierName());// 供应商
} map.put("specificationNum", goods.getSpecificationNum()); map.put("num", inboundItems.get(j).getNum());// 库 数量
BigDecimal price = BigDecimal.valueOf(inboundItems.get(j).getPrice());
BigDecimal num = BigDecimal.valueOf(inboundItems.get(j).getRealNum());
BigDecimal total = price.multiply(num);
map.put("total", total);// 采购金额 listArr.add(map);
}
} String TEMPLATE_PATH = "E://ziyuan/ruku.xlsx"; Resource resource = new FileSystemResource(TEMPLATE_PATH);
Workbook workbook = WorkbookFactory.create(resource.getInputStream());
Sheet sheet = workbook.getSheetAt(0);
final int startRow = 2;
for (int i = startRow; i < listArr.size() + startRow; i++) { int rowNum = i - startRow;
Row row = sheet.getRow(i);
if (row == null) {
row = sheet.createRow(i);
}
CellStyle contextstyle = workbook.createCellStyle();
DataFormat df = workbook.createDataFormat();
contextstyle.setDataFormat(df.getFormat("#,##0.00")); Map<String, Object> map = listArr.get(rowNum); Cell cell = row.getCell(0);
if (cell == null) {
cell = row.createCell(0);
}
cell.setCellValue(rowNum); cell = row.getCell(1);
if (cell == null) {
cell = row.createCell(1);
}
cell.setCellValue(map.get("time").toString()); cell = row.getCell(2);
if (cell == null) {
cell = row.createCell(2);
}
cell.setCellValue(map.get("year").toString()); cell = row.getCell(3);
if (cell == null) {
cell = row.createCell(3);
}
cell.setCellValue(map.get("month").toString()); cell = row.getCell(4);
if (cell == null) {
cell = row.createCell(4);
}
cell.setCellValue(map.get("day").toString()); cell = row.getCell(5);
if (cell == null) {
cell = row.createCell(5);
}
cell.setCellValue(map.get("itemNum").toString()); cell = row.getCell(6);
if (cell == null) {
cell = row.createCell(6);
}
cell.setCellValue(map.get("barCode").toString()); cell = row.getCell(7);
if (cell == null) {
cell = row.createCell(7);
}
cell.setCellValue(map.get("categoryOneName").toString()); cell = row.getCell(8);
if (cell == null) {
cell = row.createCell(8);
}
cell.setCellValue(map.get("categoryTwoName").toString()); cell = row.getCell(9);
if (cell == null) {
cell = row.createCell(9);
}
cell.setCellValue(map.get("brandName").toString());
cell = row.getCell(10);
if (cell == null) {
cell = row.createCell(10);
}
cell.setCellValue(map.get("itemName").toString());
cell = row.getCell(11);
if (cell == null) {
cell = row.createCell(11);
}
cell.setCellValue(map.get("specification").toString());
cell = row.getCell(12);
if (cell == null) {
cell = row.createCell(12);
}
cell.setCellValue(map.get("specificationNum").toString());
cell = row.getCell(13);
if (cell == null) {
cell = row.createCell(13);
}
cell.setCellValue(map.get("specificationName").toString()); cell = row.getCell(15);
if (cell == null) {
cell = row.createCell(15);
}
cell.setCellValue(map.get("num").toString());
cell = row.getCell(16);
if (cell == null) {
cell = row.createCell(16);
}
Double total=Double.valueOf(map.get("total").toString())/100;
cell.setCellValue(total); cell = row.getCell(20);
if (cell == null) {
cell = row.createCell(20);
}
cell.setCellValue(map.get("supplierName").toString());
} ExcelUtil.downloadExcel(response, workbook, "入库记录");
return APIUtil.toMap(HttpStatus.SUCCESS.getValue(), true);
}
package com.baoqilai.ddg.util;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile; /**
* Created by liuchenyu on 2017/4/8.
* Excel操作工具类
*/
public class ExcelUtil { private static final Logger logger = LoggerFactory.getLogger(ExcelUtil.class); /**
* 解析Excel
*
* @param excel 文件
* @return List集合
*/
public static List<Map<Integer, Object>> parseExcel(File excel) throws Exception {
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(excel));
HSSFSheet sheet = workbook.getSheetAt(0);
int lastRowIndex = sheet.getLastRowNum();
List<Map<Integer, Object>> excelData = new ArrayList<>(); for (int i = 1; i <= lastRowIndex; i++) {
HSSFRow row = sheet.getRow(i);
Iterator<Cell> cells = row.cellIterator();
Map<Integer, Object> rowData = new HashMap<>();
while (cells.hasNext()) {
Cell cell = cells.next();
Integer columnIndex = cell.getColumnIndex();
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { // 数值
if (DateUtil.isCellDateFormatted(cell)) {
rowData.put(columnIndex, cell.getDateCellValue());
} else {
rowData.put(columnIndex, cell.getNumericCellValue());
}
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) { // 布尔
rowData.put(columnIndex, cell.getBooleanCellValue());
} else { // 字符串
rowData.put(columnIndex, cell.getStringCellValue());
}
}
excelData.add(rowData);
}
// workbook.close();
return excelData;
} public static List<Map<Integer, Object>> parseExcel2(MultipartFile excel) throws Exception {
XSSFWorkbook workbook = new XSSFWorkbook(excel.getInputStream());
XSSFSheet sheet = workbook.getSheetAt(0);
int lastRowIndex = sheet.getLastRowNum();
List<Map<Integer, Object>> excelData = new ArrayList<>(); for (int i = 1; i <= lastRowIndex; i++) {
XSSFRow row = sheet.getRow(i);
if (null == row ) continue;
Iterator<Cell> cells = row.cellIterator();
Map<Integer, Object> rowData = new HashMap<>();
while (cells.hasNext()) {
Cell cell = cells.next();
Integer columnIndex = cell.getColumnIndex();
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { // 数值
if (DateUtil.isCellDateFormatted(cell)) {
rowData.put(columnIndex, cell.getDateCellValue());
} else {
rowData.put(columnIndex, cell.getNumericCellValue());
}
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) { // 布尔
rowData.put(columnIndex, cell.getBooleanCellValue());
} else { // 字符串
rowData.put(columnIndex, cell.getStringCellValue());
}
}
excelData.add(rowData);
}
// workbook.close();
return excelData;
} /**
* desc: 导出excel表格
* author: liuchenyu
* date: 2017/4/8 14:30
*
* @param titles Excel表各列字段名
* @param sheetname 工作表标签名
* @param data 导出的数据源
* @param filename 导出的文件名
* @param response
* @param request
* @throws Exception
*/
public static void exportExcel(String[] titles, String sheetname,
List<Map<String , Object>> data, String filename, ArrayList<String> list,HttpServletResponse response,
HttpServletRequest request) throws Exception {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(sheetname);
HSSFRow row = sheet.createRow(0);
for (int i = 0; i < titles.length; i++) {
row.createCell(i).setCellValue(titles[i]);
} for (int i = 0; i < data.size(); i++) {
Map<String , Object> obj = data.get(i);
row = sheet.createRow(i + 1); for (int j = 0; j < list.size(); j++) {
String key = list.get(j);
HSSFCell cell = row.createCell(j); cell.setCellValue(obj.get(key)==null?"--":obj.get(key)+""); }
} //filename = new String(filename.getBytes("gbk-8"), "iso8859-1");
String encoding = "utf-8";
String userAgent = request.getHeader("user-agent");
System.out.println("userAgent: " + userAgent);
if (userAgent.toLowerCase().indexOf("msie") != -1) {
encoding = "gbk";
}
filename = new String(filename.getBytes(encoding), "iso8859-1");
response.setHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
workbook.write(response.getOutputStream());
// workbook.close();
} public static void downloadExcel(HttpServletResponse response, Workbook workbook, String execelName) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
workbook.write(os);
} catch (IOException e) {
logger.error("write data to ByteArrayOutputStream fail.", e);
} byte[] content = os.toByteArray();
InputStream is = new ByteArrayInputStream(content); // 设置response参数,可以打开下载页面
//HttpServletResponse response = WebUtils.getResponse();
//response.reset();
response.setContentType("application/vnd.ms-excel;charset=utf-8");
ServletOutputStream out = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String format = sdf.format(new Date());
try {
response.setHeader("Content-Disposition",
"attachment;filename=" + new String((execelName + format + ".xls").getBytes(), "iso-8859-1"));
out = response.getOutputStream();
} catch (Exception e1) {
logger.error("write data to ServletOutputStream fail.", e1);
}
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(out); byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
} } catch (final IOException e) {
logger.error("write data to ServletOutputStream fail.", e);
} finally {
if (bis != null)
try {
bis.close();
} catch (IOException e) {
logger.error("close InputStream fail.", e);
}
if (bos != null)
try {
bos.close();
} catch (IOException e) {
logger.error("close OutputStream fail.", e);
}
}
} public static void noDataExcel(HttpServletResponse response, String fileName) {
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("1");
Row row = sheet.createRow((short) 0);
row.createCell(0).setCellValue("没有数据");
row = sheet.createRow( 1);
row.createCell(0).setCellValue("没有找到数据 - - !!!!!");
ExcelUtil.downloadExcel(response, wb, fileName);
} }
/**
* 导出列表
*/
$scope.exportList = function () {
var postData = {
page: $scope.paginationConf.currentPage,
pageSize: $scope.paginationConf.itemsPerPage,
warehouseId:$scope.warehouseId
};
if ($scope.submitted == 'pending') {
postData.status = 0;
}
if ($scope.review == 'pending') {
postData.status = 1;
}
if($scope.inboundNum){
postData.inboundNum = $scope.inboundNum;
sessionStorage.setItem('inboundNum', $scope.inboundNum);
}else {
delete postData.inboundNum;
sessionStorage.removeItem('inboundNum');
}
if($scope.linkDocType || $scope.linkDocType==''){
postData.linkDocType = $scope.linkDocType;
sessionStorage.setItem('linkDocType', $scope.linkDocType);
}else {
delete postData.linkDocType;
sessionStorage.removeItem('linkDocType');
}
if($scope.linkDocNum){
postData.linkDocNum = $scope.linkDocNum;
sessionStorage.setItem('linkDocNum', $scope.linkDocNum);
}else {
delete postData.linkDocNum;
sessionStorage.removeItem('linkDocNum');
}
if($scope.supplierName!='' &&$scope.supplierName!=undefined){
postData.supplierName = $scope.supplierName;
sessionStorage.setItem('supplierName', $scope.supplierName);
}else {
delete postData.supplierName;
sessionStorage.removeItem('supplierName');
} if($scope.supplierId){
postData.supplierId = $scope.supplierId;
sessionStorage.setItem('supplierId', $scope.supplierId);
}else if($scope.supplierId!='' && $scope.supplierId!=undefined){
$scope.supplierId = Number(sessionStorage.getItem('supplierId'));
postData.supplierId = $scope.supplierId;
}else {
delete postData.supplierId;
sessionStorage.removeItem('supplierId');
}
if($('#date_first').val() && $('#date_last').val()){
postData.createStartDate = $('#date_first').val() + ' 00:00:00';
postData.createEndDate = $('#date_last').val() + ' 23:59:59';
sessionStorage.setItem('createStartDate', $('#date_first').val());
sessionStorage.setItem('createEndDate', $('#date_last').val());
}else if(sessionStorage.getItem('createStartDate')){
$('#date_first').val(sessionStorage.getItem('createStartDate'));
$('#date_last').val(sessionStorage.getItem('createEndDate'));
postData.createStartDate = $('#date_first').val() + ' 00:00:00';
postData.createEndDate = $('#date_last').val() + ' 23:59:59';
}else {
delete postData.createStartDate;
delete postData.createEndDate;
sessionStorage.removeItem('createStartDate');
sessionStorage.removeItem('createEndDate');
}
$http({
url: adminUrl+'scp/inbound/exportList',
method: "GET",//接口方法
params: postData,
headers: {
'Content-type': 'application/json'
},
responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
var blob = new Blob([data], {type: "application/vnd.ms-excel"});
var objectUrl = URL.createObjectURL(blob);
var a = document.createElement('a');
document.body.appendChild(a);
a.setAttribute('style', 'display:none');
a.setAttribute('href', objectUrl);
var filename="入库记录.xls";
a.setAttribute('download', filename);
a.click();
URL.revokeObjectURL(objectUrl); }).error(function (data, status, headers, config) { });
};

根据Excel模板存储数据,并下载的更多相关文章

  1. 用NPOI从DataTable到Excel,向Excel模板填充数据

    DataTable---->Excel,填充数据 private IWorkbook workbook = null; private ISheet sheet = null; private ...

  2. Aspose.cell中的Excel模板导出数据

    //Excel模板导数据(Eexcel中根据DataTable中的个数,给多个Sheet中的模板赋值) public void DataSetToManyExcel(string fileName, ...

  3. Net 自定义Excel模板导出数据

    转载自:http://www.cnblogs.com/jbps/p/3549671.html?utm_source=tuicool&utm_medium=referral 1 using Sy ...

  4. kettle 使用excel模板导出数据

    通过excel进行高速开发报表: 建设思路: 1.首先制订相关的execl模板. 2.通过etl工具(kettle)能够高速的 将数据库中的数据按excel模板导出成新的excel就可以. 当中ket ...

  5. POI3.10读取Excel模板填充数据后生成新的Excel文件

    private final DecimalFormat df = new DecimalFormat("#0.00"); public void test(){ String fi ...

  6. C# Winform Excel的导出,根据excel模板导出数据

    namespace dxhbskymDemo { public partial class ExcelForm : DevExpress.XtraEditors.XtraForm { public E ...

  7. NPOI 通过excel模板写入数据并导出

    private void ToExcel(string id) { //模板文件 string TempletFileName = Server.MapPath("template.xls& ...

  8. 根据EXCEL模板填充数据

    string OutFileName = typeName+"重点源达标率" + DateTime.Now.ToString("yyyy-MM-dd");    ...

  9. 读取excel模板填充数据 并合并相同文本单元格

    try             { string OutFileName = "北京市国控企业污染源废气在线比对监测数据审核表" + DateTime.Now.ToString(& ...

随机推荐

  1. Docker基本命令与使用 —— Docker容器的网络连接(四)

    一.Docker容器的网络基础 通过ifconfig查看docker0的网络设备,docker守护进程就是通过docker0为docker的容器提供网络连接的各种服务. docker0是Linux虚拟 ...

  2. #161: 给定n*n由0和1组成的矩阵,如果矩阵的每一行和每一列的1的数量都是偶数,则认为符合条件。 你的任务就是检测矩阵是否符合条件

    试题描述 给定n*n由0和1组成的矩阵,如果矩阵的每一行和每一列的1的数量都是偶数,则认为符合条件. 你的任务就是检测矩阵是否符合条件,或者在仅改变一个矩阵元素的情况下能否符合条件. "改变 ...

  3. HTTP的长连接(持久连接)和短连接

      HTTP的长连接和短连接 本文总结&分享网络编程中涉及的长连接.短连接概念. 关键字:Keep-Alive,并发连接数限制,TCP,HTTP 一.什么是长连接 HTTP1.1规定了默认保持 ...

  4. <记录>TP5 关联模型使用(嵌套关联、动态排序以及隐藏字段)

    在数据库设计中,常常会有如下这种关联模型,分类表中一条分类对应多个商品表中的商品 如果要获得分类表中每条分类 以及 对应的商品的信息,则需要先查询分类表中的数据,然后根据结果遍历查询商品表,最后把数据 ...

  5. LevelDB源码分析-Compact

    Compaction compact由背景线程完成,代码中触发背景线程的函数为: void DBImpl::MaybeScheduleCompaction() { mutex_.AssertHeld( ...

  6. Ado.net之连接数据库

    一.Ado.net的核心 Ado.net的核心为两组重要的类,一个负责处理软件内部的实际数据(DataSet),另一个负责与外部数据系统通信(DataProvider) DataSet:包含一个或多个 ...

  7. int和string之间的转换

    #include<cstring> #include<algorithm> #include<stdio.h> #include<iostream> # ...

  8. e1000

    http://blog.csdn.net/sdulibh/article/details/41826221 http://blog.csdn.net/evenness/article/details/ ...

  9. sessionStorage实现note的功能

    功能图如图所示: 文本域中输入点击保存后的结果如图所示: 点击读取后的结果图: 选择山羊对应的按钮进行修改并点击保存后的结果: 选择山羊养对应的单选按钮进行删除操作后的结果图: 点击清空后的结果: 源 ...

  10. springcloud-知识点总结(一):Eureka

    1.Spring Cloud简介 Spring Cloud是一系列框架的有序集合.它利用Spring Boot的开发便利性巧妙地简化了分布式系统基础设施的开发,如服务发现注册.配置中心.消息总线.负载 ...