[セットトップ]javaデータベースのデータをexcelにエクスポート


プロジェクトの多くはexcelにデータをエクスポートし、データを整理分析するために使用されています.これまでのプロジェクトでは、この機能を多く使用していましたが、カーブも多く、最初のtableExcelから現在のpoiまで、最初からHSSFWorkbookを使用していました.
さらにXSSFWORkbookに着いて、一歩一歩最適化して、くだらないことは言わないで、直接始めます.
プロジェクトフレーム
1,バックグラウンド:spring+springmvc+mybatis
2,フロント:bootstrap+jQuery+ajax
3、プロジェクト管理:maven
说明Excel処理関数はpoiのjarパケットをpomに導入する必要がある.xmlはコードを導入します
<!-- POI -->  
<dependency>  
    <groupId>org.apache.poi</groupId>  
    <artifactId>poi</artifactId>  
    <version>3.8</version>  
    <exclusions>  
        <exclusion>  
            <artifactId>commons-codec</artifactId>  
            <groupId>commons-codec</groupId>  
        </exclusion>  
    </exclusions>  
</dependency>  
<dependency>  
    <groupId>org.apache.poi</groupId>  
    <artifactId>poi-ooxml</artifactId>  
    <version>3.8</version>  
</dependency>  

その他の枠组みも大体可能で、少し调整するだけで、もし问题があれば、みんなは伝言を残して讨论することができます
実装の機能説明:ユーザー情報(名前、性別、年齢)をexcelでアップロードし、データベースに保存する
具体的なコードは以下の通りです.
1,フロントhtmlコード
<span>
    <label>  :</label>
    <input id="name"  placeholder="     "  type="text">
</span>
<span>
    <label>  :</label>
    <select id="sex"  style="height: 24px;width: 163px;">
        <option value="">     </option>
		<option value="1"> </option>
		<option value="2"> </option>
    </select>
</span>
<span>
    <label>  :</label>
    <input id="age"  placeholder="     "  type="text">
</span>
<button class="btn" id="deviceExport">  </button>	   
<script type="text/javascript" src="user.js"></script>

フロントページ効果図
2,jsコード
var User = function(){
	
	this.init = function(){
		 //     excel
		$("#userExport").click(function() {
			var url =  '/user/export/';
            location.href = url + "?queryJson="+JSON.stringify(user.acquireInquireData());
		});
	};
	
	//      
	this.acquireInquireData = function(){
		var inquireCondition = {
				name:$('#name').val(),//  
				sex: $('#sex').val(),//  
				age: $('#age').val(),//  
		};
		return inquireCondition;
	};
}
	
var user;
$(function(){
	user = new User();
	user.init();
});

3,domainのuserエンティティクラス
/**  
 * @author     (     ) 
 * @erp     liguangguang 
 * @Email   [email protected]  
 * @date    2016 11 7    2:57:03  
 * @version 1.0    
 */  
public class User {  
    private  String name;  
    private String sex;  
    private String age;  
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  
    public String getSex() {  
        return sex;  
    }  
    public void setSex(String sex) {  
        this.sex = sex;  
    }  
    public String getAge() {  
        return age;  
    }  
    public void setAge(String age) {  
        this.age = age;  
    }  
}  

4,controllerレイヤコード
/**
 * @author    (     )
 * @date 2015 12 29    4:04:00
 * @Email [email protected]
 * @version 1.0
 * @return
 */
@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private UserService userService;
	/**
	 *     excel     
	 * @param queryJson
	 * @return
	 */
	@RequestMapping("/export")
	public void export(HttpServletRequest request, HttpServletResponse response,
						@RequestParam(value = "queryJson") String queryJson) {
		User user = JSON.parseObject(queryJson, User.class);
		List<User> userlList = userService.getUserForExcel(user);
		ExportExcel<User> ee= new ExportExcel<User>();
		String[] headers = { "  ", "  ", "  ", "  " };
		String fileName = "     ";
		ee.exportExcel(headers,userlList,fileName,response);
	}
}
5サービス層コード
public interface UserService {  
  
    /**
	 *               ,    ,  excel      
	 * @param userDeviceVo
	 * @return
	 */
	public List<User> getUserDeviceForExcel(User user); 
  
}  
,service実装レイヤコード
/**
 * @author     (     )
 * @date 2015 12 29    3:43:08 
 * @Email [email protected] 
 * @version 1.0
 * @return
 */

public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserDao  userDao;
/**
	 *               ,    ,  excel      
	 * @param userDeviceVo
	 * @return
	 */
	@Override
	public List<User> getUserDeviceForExcel(User user) {
		List<User> list = userDeviceDao.getUserForExcel(user);
		Integer order;
		for (int i = 0; i < list.size(); i++) {
			order = i + 1;
			list.get(i).setOrder(order.toString());
			if (list.get(i).getSex().equals("1")) {
				list.get(i).setSex(" ");
			} else {
				list.get(i).setSex(" ");
			}
		}
		return list;
	}
}

6 daoレイヤコード
public interface UserDao {  
  
  /**
	 *               ,    ,  excel      
	 * @param userDeviceVo
	 * @return
	 */
	List<User> getUserForExcel(User user);

  
}  

7 mybatisコード
  <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="XXX .UserDao">

  <!--              ,    ,  excel      -->
    <select id="getUserForExcel" parameterType="User" resultType="User">
        select name,sex,age
        from juser_table 
        where  1=1 and 
        <if test="name != null and name !=''">and  name=#{name}</if>
		<if test="sex != null and sex !=''">and  sex=#{sex}</if>
		<if test="age != null and age !=''">and  age=#{age}</if>
    </select>
</mapper>

8、メインイベントが来て、リストデータをexcelに書き込むコードは以下の通りです.
package com.jd.xe.web.service.userDevice;

import java.io.BufferedOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.jd.xe.web.utils.DateUtil;


/** 
 * @author     (     )
 * @erp     liguangguang
 * @Email   [email protected] 
 * @date    2016 7 18    9:03:29 
 * @version 1.0   
 */
public class ExportExcel<T> {
	public void exportExcel(String[] headers,Collection<T> dataset, String fileName,HttpServletResponse response) {
		//        
		XSSFWorkbook workbook = new XSSFWorkbook();
		//       
		XSSFSheet sheet = workbook.createSheet(fileName);
		//           15   
		sheet.setDefaultColumnWidth((short) 20);
		//        
		XSSFRow row = sheet.createRow(0);
		for (short i = 0; i < headers.length; i++) {
			XSSFCell cell = row.createCell(i);
			XSSFRichTextString text = new XSSFRichTextString(headers[i]);
			cell.setCellValue(text);
		}
		try {
			//       ,     
			Iterator<T> it = dataset.iterator();
			int index = 0;
			while (it.hasNext()) {
				index++;
				row = sheet.createRow(index);
				T t = (T) it.next();
				//     ,  javabean       ,    getXxx()       
				Field[] fields = t.getClass().getDeclaredFields();
				for (short i = 0; i < headers.length; i++) {
					XSSFCell cell = row.createCell(i);
					Field field = fields[i];
					String fieldName = field.getName();
					String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
					Class tCls = t.getClass();
					Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
					Object value = getMethod.invoke(t, new Object[] {});
					//                
					String textValue = null;
					//                 
					if(value != null && value != ""){
						textValue = value.toString();
					}
					if (textValue != null) {
						XSSFRichTextString richString = new XSSFRichTextString(textValue);
						cell.setCellValue(richString);
					}
				}
			}
			getExportedFile(workbook, fileName,response);
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	/**
	 * 
	 *     :        EXCEL  
	 * @return
	 */
	public void getExportedFile(XSSFWorkbook workbook, String name,HttpServletResponse response) throws Exception {
		BufferedOutputStream fos = null;
		try {
			String fileName = name+DateUtil.parseSmallDate(new Date()) + ".xlsx";
			response.setContentType("application/x-msdownload");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ));
			fos = new BufferedOutputStream(response.getOutputStream());
			workbook.write(fos);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fos != null) {
				fos.close();
			}
		}
	}

}

これで全体のコードはすでに完成して、もし何か分からない地方があるならば、評論することができて、私は直ちにみんなに返事することができて、焦っているならばQQ:826331692私に連絡することができて、互いに勉強して、共に進歩します.