Browse Source

通过jxls导出大量数据的测试。

yuj 7 years ago
parent
commit
46e634054b

+ 5 - 1
pom.xml

@@ -61,6 +61,9 @@
 			</properties>
 		</profile>
 	</profiles>
+	<properties>
+		<spring.version>4.2.8.RELEASE</spring.version>
+	</properties>
 	<dependencies>
 		<dependency>
 			<groupId>javax.servlet</groupId>
@@ -125,7 +128,6 @@
 		<dependency>
 			<groupId>org.springframework</groupId>
 			<artifactId>spring-webmvc</artifactId>
-			<version>4.2.8.RELEASE</version>
 		</dependency>
 		<dependency>
 			<groupId>org.springframework</groupId>
@@ -526,6 +528,7 @@
 				<filtering>true</filtering>
 				<excludes>
 					<exclude>**/*.xls</exclude>
+					<exclude>**/*.xlsx</exclude>
 				</excludes>
 			</resource>
 			<!-- xls文件不能filter处理,需区分出来 -->
@@ -534,6 +537,7 @@
 				<filtering>false</filtering>
 				<includes>
 					<include>**/*.xls</include>
+					<include>**/*.xlsx</include>
 				</includes>
 			</resource>
 		</resources>

+ 119 - 13
src/main/java/com/uas/platform/b2c/core/support/view/JxlsxExcelView.java

@@ -1,10 +1,26 @@
 package com.uas.platform.b2c.core.support.view;
 
+import com.uas.platform.b2c.core.utils.ContextUtils;
+import com.uas.platform.b2c.core.utils.StringUtilB2C;
+import com.uas.platform.core.exception.IllegalOperatorException;
+import javassist.runtime.Desc;
+import net.sf.jxls.transformer.XLSTransformer;
+import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
+import org.apache.poi.poifs.filesystem.POIFSFileSystem;
 import org.apache.poi.ss.usermodel.Workbook;
+import org.apache.poi.ss.usermodel.WorkbookFactory;
+import org.springframework.core.io.Resource;
+import org.springframework.core.io.support.LocalizedResourceHelper;
+import org.springframework.web.servlet.support.RequestContextUtils;
 import org.springframework.web.servlet.view.document.AbstractXlsxView;
 
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
+import java.io.*;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.util.HashMap;
+import java.util.Locale;
 import java.util.Map;
 
 /**
@@ -15,15 +31,10 @@ import java.util.Map;
  */
 public class JxlsxExcelView extends AbstractXlsxView {
 
-    /**
-     * 文件名
-     */
-	private String fileName;
-
 	/**
 	 * 导入.xls格式文件
 	 */
-	private static final String EXTENSION = ".xls";
+	private static final String EXTENSION = ".xlsx";
 
 	/**
 	 *  .xls 表格
@@ -35,22 +46,117 @@ public class JxlsxExcelView extends AbstractXlsxView {
 	 */
 	public static final String EXCEL_XLSX = "xlsx";
 
+	/**
+	 * url生成模板的路径
+	 */
+	private String url = "C:\\Users\\yuj\\Downloads\\xls\\template\\";
+
+	/**
+	 * 模板路径
+	 */
+	private String templateUrl;
+
+
+	/**
+	 * 文件名
+	 */
+	private String fileName;
+
+	public JxlsxExcelView() {
+	}
+
+	public JxlsxExcelView(String fileName, String templateUrl) {
+		this.fileName = fileName;
+		this.templateUrl = templateUrl;
+	}
+
 	@Override
-	protected void buildExcelDocument(Map<String, Object> map, Workbook workbook, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
-/*		if (model == null)
-			map = new HashMap<String, Object>();
-		map.put("export", new Export());
+	protected void buildExcelDocument(Map<String, Object> map, Workbook workbook, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
+		if (map == null) {
+			map = new HashMap<>();
+		}
 		XLSTransformer transformer = new XLSTransformer();
 		transformer.transformWorkbook(workbook, map);
-		response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8") + EXTENSION);*/
+		response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8") + EXTENSION);
 	}
 
 	@Override
 	protected Workbook createWorkbook(Map<String, Object> model, HttpServletRequest request) {
-		Object filePath = model.get("filePath");
-		return super.createWorkbook(model, request);
+//		File file = null;
+//		try {
+//			file = copyFile(request);
+//		} catch (IOException e) {
+//			e.printStackTrace();
+//		}
+		LocalizedResourceHelper helper = new LocalizedResourceHelper(ContextUtils.getApplicationContext());
+		Locale userLocale = RequestContextUtils.getLocale(request);
+		Resource inputFile = helper.findLocalizedResource(templateUrl, EXTENSION, userLocale);
+		Workbook workbook = null;
+		try {
+			workbook = getWorkbook(inputFile.getFile());
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+		return workbook;
 	}
 
+	/**
+	 * 复制模板文件
+	 */
+	private File copyFile(HttpServletRequest request) throws IOException {
+		if (StringUtilB2C.isEmpty(fileName)) {
+			throw new IllegalOperatorException("文件名称不存在");
+		}
+		if (StringUtilB2C.isEmpty(templateUrl)) {
+			throw new IllegalOperatorException("模板文件不存在");
+		}
+		LocalizedResourceHelper helper = new LocalizedResourceHelper(ContextUtils.getApplicationContext());
+		Locale userLocale = RequestContextUtils.getLocale(request);
+		Resource inputFile = helper.findLocalizedResource(templateUrl, EXTENSION, userLocale);
+		inputFile.isOpen();
+		inputFile.isReadable();
+		inputFile.getFile();
+		if (inputFile == null || !inputFile.exists()) {
+			throw new IllegalOperatorException("模板文件不存在");
+		}
+		File destFile = new File(this.url + fileName + System.currentTimeMillis() + EXTENSION);
+		if (!destFile.exists()) {
+			destFile.createNewFile();
+		}
+		FileInputStream ins = new FileInputStream(new File(inputFile.getURL().getFile()));
+		FileOutputStream out = new FileOutputStream(destFile);
+		byte[] b = new byte[1024];
+		int n = 0;
+		while ((n = ins.read(b)) != -1) {
+			out.write(b, 0, n);
+		}
+		ins.close();
+		out.close();
+		return destFile;
+	}
+
+	/***
+	 * 根据文件获取workbook
+	 * @param file 文件
+	 * @return 返回值
+	 */
+	private Workbook getWorkbook(File file) {
+		if (file == null || !file.exists()) {
+			throw new IllegalOperatorException("模板文件不存在");
+		}
+		Workbook workbook = null;
+		try {
+			workbook = WorkbookFactory.create(file);
+		} catch (IOException e) {
+			e.printStackTrace();
+		} catch (InvalidFormatException e) {
+			e.printStackTrace();
+		}
+		return workbook;
+	}
+
+
+
 	//
 //	public JxlsxExcelView(String tplPath, String fileName) {
 //		super();

+ 36 - 0
src/main/java/com/uas/platform/b2c/prod/commodity/controller/ProductController.java

@@ -6,11 +6,13 @@ import com.uas.platform.b2c.core.constant.SplitChar;
 import com.uas.platform.b2c.core.support.SystemSession;
 import com.uas.platform.b2c.core.support.log.UsageBufferedLogger;
 import com.uas.platform.b2c.core.support.view.JxlsExcelView;
+import com.uas.platform.b2c.core.support.view.JxlsxExcelView;
 import com.uas.platform.b2c.prod.commodity.facade.ProductFacade;
 import com.uas.platform.b2c.prod.commodity.model.*;
 import com.uas.platform.b2c.prod.commodity.service.GoodsService;
 import com.uas.platform.b2c.prod.commodity.service.ProductService;
 import com.uas.platform.b2c.prod.commodity.type.ProductConstant;
+import com.uas.platform.b2c.prod.product.component.modal.ComponentInfo;
 import com.uas.platform.b2c.trade.support.CodeType;
 import com.uas.platform.b2c.trade.support.ResultMap;
 import com.uas.platform.core.logging.BufferedLoggerManager;
@@ -483,4 +485,38 @@ public class ProductController {
         USELOG.log("卖家中心物料", "单个物料录入操作");
 	    return productService.editOne(jsonObject);
     }
+
+	/**
+	 * 批量导出的测试接口
+	 * @return
+	 */
+	@RequestMapping(value = "/test/xls", method = RequestMethod.GET)
+    public ModelAndView testDownLoad() {
+		long l = System.currentTimeMillis();
+		ModelAndView modelAndView = new ModelAndView();
+		modelAndView.addObject("data", productService.getProductByEnuuByCommonDao());
+		modelAndView.setView(new JxlsExcelView("classpath:jxls-tpl/trade/test", "测试xls"));
+		logger.info("商品批次", "下载批量上架商品的Excel模板");
+		long l1 = System.currentTimeMillis();
+		System.out.println("装换成Excel" + (l1 - l));
+		return modelAndView;
+	}
+
+
+	/**
+	 * 批量导出的测试接口
+	 * @return
+	 */
+	@RequestMapping(value = "/test/xlsx", method = RequestMethod.GET)
+	public ModelAndView testDownLoadxlsx() {
+		long l = System.currentTimeMillis();
+		ModelAndView modelAndView = new ModelAndView();
+		modelAndView.addObject("data", productService.getProductByEnuuByCommonDao());
+		modelAndView.setView(new JxlsxExcelView("测试xlsx", "classpath:jxls-tpl/trade/test"));
+		logger.info("商品批次", "下载批量上架商品的Excel模板");
+		long l1 = System.currentTimeMillis();
+		System.out.println("装换成Excel" + (l1 - l));
+		return modelAndView;
+	}
+
 }

+ 8 - 0
src/main/java/com/uas/platform/b2c/prod/commodity/dao/ProductDao.java

@@ -141,6 +141,14 @@ public interface ProductDao extends JpaSpecificationExecutor<Product>, JpaReposi
      */
     List<Product> findByEnUUAndCmpUuId(Long enuu, String uuid);
 
+
+    /**
+     * 通过企业uu、标准器件uuid获取标准物料信息
+     * @param enuu 企业的enuu
+     * @return List<Product>
+     */
+    List<Product> findByEnUU(Long enuu);
+
     /**
      * 通过企业uu、标准器件uuid获取标准物料信息
      * @param uuid 器件的uuid

+ 15 - 0
src/main/java/com/uas/platform/b2c/prod/commodity/service/ProductService.java

@@ -403,4 +403,19 @@ public interface ProductService {
      * @return ResultMap
      */
     ResultMap checkCriterion(Product product);
+
+
+    /**
+     * 企业的enuu
+     *
+     * @return List<Product>
+     */
+    List<Product> getProductByEnuu();
+
+
+    /**
+     * 测试通过jdbctemplate 获取制定对象
+     * @return
+     */
+    List<Product> getProductByEnuuByCommonDao();
 }

+ 37 - 0
src/main/java/com/uas/platform/b2c/prod/commodity/service/impl/ProductServiceImpl.java

@@ -109,6 +109,7 @@ import org.springframework.data.domain.Page;
 import org.springframework.data.domain.PageImpl;
 import org.springframework.data.domain.Sort;
 import org.springframework.data.jpa.domain.Specification;
+import org.springframework.jdbc.core.BeanPropertyRowMapper;
 import org.springframework.jdbc.core.JdbcTemplate;
 import org.springframework.jdbc.core.ParameterizedPreparedStatementSetter;
 import org.springframework.jdbc.core.StatementCallback;
@@ -2876,4 +2877,40 @@ public class ProductServiceImpl implements ProductService {
         goods = goodsDao.save(goods);
         LOGGER.log("上架商品", "新增上架商品", "通过卖家中心单个物料上传新增上架商品", goods.getCode(), goods.getId());
     }
+
+    /**
+     * 企业的enuu
+     *
+     * @return
+     */
+    @Override
+    public List<Product> getProductByEnuu() {
+        long l = System.currentTimeMillis();
+        List<Product> products = productDao.findByEnUU(10049056L);//数量是10002条
+        long l1 = System.currentTimeMillis();
+        System.out.println("获取数据库数据的时间是:" + (l1 - l));
+        return products;
+    }
+
+    /**
+     * 测试通过jdbctemplate 获取制定对象
+     *
+     * @return
+     */
+    @Override
+    public List<Product> getProductByEnuuByCommonDao() {
+        String sql = "select pr_code,pr_pcmpcode from products where pr_enuu = %d";
+        List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(String.format(sql, 10041559L)); // 68136条数据
+        List<Product> list = new ArrayList<>();
+        Product p = null;
+        for (Map<String, Object> objectMap : queryForList) {
+            p = new Product();
+            Object pr_code = objectMap.get("pr_code");
+            p.setProdNum(StringUtilB2C.getStr(pr_code));
+            Object prPcmpcode = objectMap.get("pr_pcmpcode");
+            p.setPcmpcode(StringUtilB2C.getStr(prPcmpcode));
+            list.add(p);
+        }
+        return list;
+    }
 }

BIN
src/main/resources/jxls-tpl/trade/goods.xls


BIN
src/main/resources/jxls-tpl/trade/test.xls


BIN
src/main/resources/jxls-tpl/trade/test.xlsx