您的位置:首页 > 数据库

input file 文件上传下载 查询数据库数据并导出Excel

2018-01-09 14:28 871 查看
项目环境基于angular.js

HTML 列表:

<div class="table-container">
<table class="table table-striped table-bordered table-hover" id="apMaterialsInfoDatatable">
<thead>
<tr dictionary="row" class="heading">
<th   data-options="{mData:null}">序号</th>
<th width="35%" data-options="{mData:'materialName', orderable:true, sClass: ''}">材料名称</th>
<th width="30%" data-options="{mData:'materialType', dictId:'LXBT_SQCLFL', orderable:true, sClass: ''}" >申请材料分类</th>
<th width="30%" data-options="{toolbar:'renderFileOpts',pojoName:'apMaterialsInfo'}" >操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>

HTML 按钮

<div class="layui-form-item">

                           <div ng-show="!isDetail()">
         
  <label for="fileInput" class="file-button">选择文件</label>
          <input type="file" name="file" id="fileInput" onchange="angular.element(this).scope().operation.doChoose()" style="opacity:0;filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0);width:20px;"
/>
  </div>

                        </div>

/**************文件操作开始*********************/

$scope.operation.renderFileOpts = function(data, type, full, pojoName) {
var ops = '<a href="#" ng-click="operation.removeFile('+ data + ')"  ng-show="!isDetail()">删除</a>'
+' <a href="/lxbt/lxbt/ctrl/apMaterialsInfo/dowload/' + data + '" >下载</a>'
return ops;
};

var resultData = {};
$scope.operation.doChoose = function() {
var file = document.querySelector("#fileInput").files[0];
if(!(file == null || file == "" || file == undefined)){
checkFile(file);
if(resultData.flag == false)
{
layer.msg(resultData.errorMessage);
return false;
}

//显示选择文件信息

$scope.apMaterialsInfo.apBasicInfoId = $scope.apMaterialsInfo.apBasicInfoId;
$scope.apMaterialsInfo.materialName = file.name;
$scope.apMaterialsInfo.materialSize = (file.size / 1014).toFixed(1);

        $scope.$apply();
//实时上传
$scope.saveApMaFile('apMaterialsInfoForm');
}else
{
layer.msg("文件选择失败,请重新选择!");
return false;
}
};

//清除input file 选择值
$scope.deleteApMaFile  = function(id) 
{
var file = document.querySelector("#"+ id).files[0];
if(!file)
{
file.value = ''; 
}
}

//保存

$scope.saveApMaFile = function(form) {

//form表单校验

if ($scope.errFormValidator(form))
{
$scope.deleteApMaFile("fileInput");
return;
}

//表单校验失效,故在此手动校验是否为空

if($scope.apMaterialsInfo.materialType == null )
{
$scope.deleteApMaFile("fileInput");
layer.msg("保存失败,请选择申请材料文件分类!");

//选择文件按钮显示

$scope.creatBtn.apMaterialsInfoSaveBtn = true;
return;
}
var formData = new FormData();
var file = document.querySelector("#fileInput").files[0];
if(file && resultData.flag == true)
{
formData.append("file", file); 
}else
{
$scope.deleteApMaFile("fileInput");
layer.msg("保存失败,请重新选择文件!");
return;
}
formData.append("businessId", $scope.apMaterialsInfo.apBasicInfoId);
formData.append("materialType", $scope.apMaterialsInfo.materialType);
$.ajax({
url : "/ctrl/apMaterialsInfo/upload",
type : "POST",
data : formData,
contentType : false,
processData : false,
success : function(data) {
$scope.deleteApMaFile("fileInput");
resultData = {};

//选择文件、保存按钮隐藏

$(".file-button").hide();
$scope.submitFilter('apMaterialsInfo', true);
$scope.creatBtn.apMaterialsInfoSaveBtn = false;
layer.msg("保存成功!");

},
error : function() {
layer.msg("保存失败!");
}
});
};

// 校验文件
checkFile = function(file) {
var flag = true;
var errorMessage = "";
if (file == null || file == "" || file == undefined) {
flag = false;
errorMessage += "请重新选择文件!"
} else {

if (file.size < 0 || file.size > 1024 * 1024 * 2) {
flag = false;
errorMessage += "文件大小超过2MB!"
}
if (file.name.length < 0 || file.name.length > 50) {
flag = false;
errorMessage += "文件名称过长!"
}
//判断是否重复
var tab=document.getElementById("apMaterialsInfoDatatable");
       var rowsLen= tab.rows.length;
       var count = 0;
       var reFlag = true;
       if(rowsLen > 1 && tab.rows[1].cells.length > 1 )

        {
       
for(var i=1;i<rowsLen;i++)
       

       
val = tab.rows[i].cells[1].innerText;
       
if(val == file.name)
   
{
       
reFlag = false;
   
count++;
   
}
       }
       if(reFlag == false)
       {
       
flag = false;
       
errorMessage += "文件名称重复"+ count +"次!"
       }

        }
}
resultData.flag = flag;
resultData.errorMessage = errorMessage;
};

//删除已选择未提交文件
removeChooseFile = function(obj) {
var tr = obj.parentNode.parentNode;
var tbody = tr.parentNode;
tbody.removeChild(tr);
// 只剩行首时删除表格
if (tbody.rows.length == 1) {
return false;
}
}

$scope.operation.removeFile = function(id) {
$.ajax({
url : "/ctrl/apMaterialsInfo/removeFile/" + id,
type : "GET",
success : function(data) {
$scope.submitFilter('apMaterialsInfo', true);
},
error : function() {
layer.msg("删除失败!");
}
});

};

/*********文件操作结束*****************/

Java 后台



/**
* 上传
* @author waz 
* @param file
* @param businessId
* @param materialType
* @return ApMaterialsInfo
*/
@RequestMapping(path = "/ctrl/apMaterialsInfo/upload",method = RequestMethod.POST)
@ResponseBody
@EncryptIgnore
public ApMaterialsInfo upload(@RequestParam("file") MultipartFile file ,@RequestParam("businessId") Long businessId
,@RequestParam("materialType") String materialType ,HttpServletRequest request){
ApMaterialsInfo apMaterialsInfo = new ApMaterialsInfo();
try{
apMaterialsInfo.setMaterialName(file.getOriginalFilename());
apMaterialsInfo.setMaterialSize(file.getSize());
apMaterialsInfo.setMaterialContent(file.getBytes());
apMaterialsInfo.setMaterialType(materialType);
apMaterialsInfo.setApBasicInfoId(businessId);
apMaterialsInfo = apMaterialsInfoService.saveFile(apMaterialsInfo);
}
catch(Exception e)
{
e.printStackTrace();
}
return apMaterialsInfo;
}

/**
* 下载
* @author waz 
* @param Id
*/
@RequestMapping(path = "/ctrl/apMaterialsInfo/dowload/{id}", method = RequestMethod.GET)
public void preview1(@PathVariable Long id,HttpServletResponse response){
ApMaterialsInfo apMaterialsInfo = apMaterialsInfoService.findOne(id);
String fileName = apMaterialsInfo.getMaterialName();
response.setCharacterEncoding("UTF-8");
response.setContentType("APPLICATION/OCTET-STREAM");
response.addHeader("Content-Disposition","apMaterialsInfo; filename=" + fileName + "");
OutputStream os = null;
try {
os = response.getOutputStream();
os.write(apMaterialsInfo.getMaterialContent());
os.flush();
}
catch(IOException e){
log.warn("Throw IOException where downloading file .file id is "+ id, e);
}
finally {
if(os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

/**
* 删除
* @author waz 
* @param id
* @return ApMaterialsInfo
*/
@RequestMapping(path = "/ctrl/apMaterialsInfo/removeFile/{id}", method = RequestMethod.GET)
@ResponseBody
public ApMaterialsInfo remove(@PathVariable Long id,HttpServletResponse response) {
ApMaterialsInfo apMaterialsInfo = apMaterialsInfoService.findOne(id);
apMaterialsInfoService.delete(id);
return apMaterialsInfo;
}

dao层代码

/**
* 上传保存
* @author waz 
* @return ApRevMaterialsInfo
*/
public <T extends ApMaterialsInfo> T saveFile(T apMaterialsInfo) {
MultipartFile file = apMaterialsInfo.getFile();
if (file != null) {
apMaterialsInfo.setMaterialName(file.getOriginalFilename());
apMaterialsInfo.setMaterialSize(file.getSize());
try {
apMaterialsInfo.setMaterialContent(file.getBytes());
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
return apMaterialsInfoRepository.save(apMaterialsInfo);
}

//彩蛋 Excel 导出

/**
* 人员信息查询 -- 导出

* @author zcl
* @param baOtherInfo
* @param response
* @param request
*/
@RequestMapping(path = "/ctrl/testClass/exportExccel", method = RequestMethod.PUT)
@ResponseBody
public void exportExccel(@RequestBody TestClass testClass,HttpServletResponse response, HttpServletRequest request) {
//拼接查询条件
String sqlEnd = ""; 
if(testClass != null){
if(!(testClass.getName() == null || testClass.getName() == ""))
sqlEnd += " and class.name like '%" + testClass.getName() + "%'";
}
String sqlCount = " select count(*) from test_class class  where class.use_flag = 1 " + sqlEnd;
Long count = testClassService.queryForCount(sqlCount);
User user = UserSession.getUser();
String fileName = "导出测试" + "_" + user.getName();
try {
if(count == 0)
response.getWriter().print("0");
else if(count >50000)
response.getWriter().print("1");
else {

fileName += "_"+Tools.getDateStr(new Date(), "yyyyMMddHHmmss")+".xls";

String webRootPath = request.getSession().getServletContext().getRealPath("");

String pathName = null;
if(System.getProperties().getProperty("os.name").toLowerCase().contains("windows")){
pathName = webRootPath +"\\resources\\backDownload\\"+fileName;
}else {//if(System.getProperties().getProperty("os.name").toLowerCase().contains("linux")){
pathName = webRootPath + File.separator +"resources"+ File.separator + "backDownload"+ File.separator+fileName; 
}

File file = new File(pathName);
if(!file.exists())
{
file.createNewFile();
}

byte[] data = null;
data = testClassService.getSimpleExcel(sqlEnd);

ByteArrayInputStream bis = new ByteArrayInputStream(data);
OutputStream stream = new FileOutputStream(pathName);
BufferedOutputStream bos = new BufferedOutputStream(stream);
int bytesRead = 0;
byte buffer[] = new byte[8192];
while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) 
bos.write(buffer, 0, bytesRead);
bos.close();
stream.close();

response.getWriter().print(fileName);
}
} catch (IOException e) {
log.error("Throw IOException where export ryxxcx_excel named "
+ fileName + ". gosUser id is " + user.getId(), e);
}
}

//dao层代码

/**
* 获取excel

* @author zcl
* @param sqlEnd
* @return
* @throws IOException
*/
public byte[] getSimpleExcel(String sqlEnd) throws IOException {

String headString = "序号,姓名";
String[] head = headString.split(",");
String sql = "select class.id,class.name " +
" from test_class class "+
       " where class.use_flag = 1 " + sqlEnd + " order by class.id";
return this.getSimpleExcelDate(sql, head);
}

/**
* 获取excel字节流

* @author zcl
* @param sql
* @param head
* @return
* @throws IOException 
*/
public byte[] getSimpleExcelDate(String sql, String[] head) throws IOException{

HSSFWorkbook excelObj = new HSSFWorkbook();
this.creatSimpleSheet(excelObj, head, sql);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
excelObj.write(baos);
byte[] excelData = baos.toByteArray();
baos.close();

return excelData;
}

  /**

  * 创建工作簿

  * 

  * @param excelObj

  * @param workSheet

  * @param head

  * @param cellStyle 

  * @param headStyle 

  * @param sql

  */

  public void creatSimpleSheet(HSSFWorkbook excelObj, String[] head, String sql){

 

  SqlRowSet sqlRowSet = jdbcTemplate.queryForRowSet(sql);

  HSSFSheet workSheet = excelObj.createSheet();
this.setSimpleColumnWidth(workSheet);
HSSFCellStyle headStyle = this.getHeadStyle0(excelObj);
HSSFCellStyle cellStyle = this.getCellStyle(excelObj);
int excelRowIndex = 0;
HSSFRow _row0 = workSheet.createRow(excelRowIndex++);
_row0.setHeightInPoints(20);
CellRangeAddress cellRangeAddres = new CellRangeAddress(0,0,0,16);
workSheet.addMergedRegion(cellRangeAddres);
HSSFCell _row0cell0 = _row0.createCell(0);
_row0cell0.setCellStyle(headStyle);
_row0cell0.setCellValue("文件导出测试");

HSSFRow _row1 = workSheet.createRow(excelRowIndex++);

_row1.setHeightInPoints(20);

for(int i =0; i<head.length; i++)
{
HSSFCell cell = _row1.createCell(i);
cell.setCellStyle(headStyle);

cell.setCellValue(head[i]);
}

while(sqlRowSet.next()){
HSSFRow row = workSheet.createRow(excelRowIndex++);
int columnNumber = 0;
HSSFCell _cell = row.createCell(columnNumber++);
_cell.setCellStyle(cellStyle);

_cell.setCellValue(""+(-2+excelRowIndex));

for(int i=1; i<=sqlRowSet.getMetaData().getColumnCount();i++){
HSSFCell cell = row.createCell(columnNumber++);
cell.setCellStyle(cellStyle);
cell.setCellValue(sqlRowSet.getString(i));
}
}

  }

 

  /**

  * 设置列宽

  * 

  * @author zcl

  * @param workSheet

  */

  public void setSimpleColumnWidth(HSSFSheet workSheet){

  workSheet.setColumnWidth(0, (256*6));
//序号
workSheet.setColumnWidth(1, (256*15));
//姓名

  }

 
/**

  * 设置表头样式

  * 

  * @param excelObj

  * @param cell

  * @return 

  */

  public HSSFCellStyle getHeadStyle0(HSSFWorkbook excelObj){

  HSSFCellStyle style = excelObj.createCellStyle();

 

  /*

  * 单元格样式

  */
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//左边框
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//右边框
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//上边框
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//下边框
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//水平居中

  style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
//垂直居中

  /*

  * 单元格字体

  */

  HSSFFont font = excelObj.createFont();

  font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//粗体

  font.setFontName("宋体");
//宋体

  font.setFontHeight((short)(15*20));
//大小

  style.setFont(font);

 
return style;

  }

 

  /**

  * 设置单元格样式

  * 

  * @param excelObj

  * @param cell

  * @return 

  */

  public HSSFCellStyle getCellStyle(HSSFWorkbook excelObj){

  HSSFCellStyle style = excelObj.createCellStyle();

 

  /*

  * 单元格样式

  */

  style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//左边框
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//右边框
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//上边框
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//下边框

/*

  * 单元格字体

  */

  HSSFFont font = excelObj.createFont();

  font.setFontName("宋体");
//宋体

  style.setFont(font);

 

  return style;

  }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐