Java将数据存入DBF并打zip包下载

前端代码:

function f_pfgjdc() {
       var kmdm=$("#kmdm").val();
       if(kmdm==null||kmdm==""){
           alert("请先选择科科目");
           return;
       }
       if(!confirm("你确定要导出科目的判分轨迹吗?")){
           return;
       }
       //$("#loadingImage").css("display","block");
       $("#kmxxForm").attr("target","fileDownloadFrame");
       //使用表单提交
       $("#kmxxForm").attr("action","cjgl.do?method=expKmPfgj&kmdm="+kmdm);
       $("#kmxxForm").submit();
   }

逻辑层代码:

public ActionForward expKmPfgj(ActionMapping mapping, ActionForm form,
								   HttpServletRequest request, HttpServletResponse response) {
		String msg=null;		//提示信息
		String sql="";			//sql细分档
		List> dataListXf;//查询的结果存入这个List
		SystemBusiness utils=new SystemBusiness();	 //工具类,在下面会贴代码
		response.setContentType("application/json;charset=gb2312");
		try{
			String kmdm=request.getParameter("kmdm");
			if(kmdm==null){
				msg="缺少科目参数!";
				return utils.actionReturnErrorPage(mapping, request, msg, "actFwdRs");
			}
			//获取科目名称
			HashMap kmMap=(HashMap)IbatisDAO.getObjectByIbatis("getKmxxByKmdm_kmdm", kmdm);
			String kmmc=kmMap==null?"":kmMap.get("KMMC").toString();
			//先从Java里把DBF的信息定义好
			List dbfColList=new ArrayList();	//dbf字段名
			List dbfColMeanList=new ArrayList();	//dbf字段含义
			List dbfColTypeList=new ArrayList();	//dbf字段类型
			List dbfColLenList=new ArrayList();	//dbf字段长度
			//赋值
			dbfColList.add("bmh");
			dbfColMeanList.add("保密号");
			dbfColTypeList.add("c");
			dbfColLenList.add(40);

			dbfColList.add("kmdm");
			dbfColMeanList.add("科目代码");
			dbfColTypeList.add("c");
			dbfColLenList.add(15);

			dbfColList.add("zt");
			dbfColMeanList.add("状态");
			dbfColTypeList.add("c");
			dbfColLenList.add(5);

			dbfColList.add("yh");
			dbfColMeanList.add("用户");
			dbfColTypeList.add("c");
			dbfColLenList.add(5);

			dbfColList.add("sj");
			dbfColMeanList.add("判分时间");
			dbfColTypeList.add("c");
			dbfColLenList.add(32);

			dbfColList.add("pf");
			dbfColMeanList.add("判分");
			dbfColTypeList.add("c");
			dbfColLenList.add(10);

			dbfColList.add("scsj");
			dbfColMeanList.add("生成时间");
			dbfColTypeList.add("c");
			dbfColLenList.add(30);

			dbfColList.add("ksh");
			dbfColMeanList.add("考生号");
			dbfColTypeList.add("c");
			dbfColLenList.add(20);
			//查询数据的SQL,这里要和上面赋值的保持同步
			sql = "select b.bmhh,a.kmdm,a.zt,a.yh,to_char(a.sj,'yyyy-mm-dd hh24:mi:ss') sj,a.pf,to_char(a.scsj,'yyyy-mm-dd hh24:mi:ss') scsj,b.ksh from T_PFJD a,T_SJJD b where a.kmdm='"+kmdm+"' and a.kmdm=b.kmdm and a.bmh=b.bmh order by a.bmh,a.yh";
			dataListXf=IbatisDAO.getListByIbatis("getHashMap_ibatis", sql);
			//获取文件位置(临时路径)
			String fileLocString=utils.getFileTempDir(request);//调用工具类,代码下面有贴
			//生成轨迹文件(判分)
			String serverFile1=fileLocString+"\\"+kmmc+"判分轨迹.dbf";	//用户的唯一号做标记,服务器保存用
			msg=utils.writeDbf(serverFile1, dbfColList, dbfColMeanList, dbfColTypeList, dbfColLenList, dataListXf);
			if(msg!=null){//生成出错
				return utils.actionReturnErrorPage(mapping, request, msg, "actFwdRs");
			}

			//生成DBF字段说明文件
			String serverFile2=fileLocString+"\\"+kmmc+"判分轨迹字段说明.txt";
			List textList=new ArrayList();//写入内容
			textList.add("dbf字段含义说明");
			textList.add("");
			for(int i=0;i fileList=new ArrayList();
			fileList.add(serverFile1);
			fileList.add(serverFile2);
			String serverFile=fileLocString+"\\"+kmmc+"判分轨迹.zip";
			utils.createZip(serverFile, fileList);
			File file=new File(serverFile);
			if(!file.isFile() || !file.exists()){
				msg="生成下载文件失败!";
				return utils.actionReturnErrorPage(mapping, request, msg, "actFwdRs");
			}
			//下载文件
			utils.downloadFile(response, serverFile, kmmc+"判分轨迹.zip");
		}catch(Exception e){
			msg="下载时发生异常!\n"+e;
			return utils.actionReturnErrorPage(mapping, request, msg, "actFwdRs");
		}
		return null;
	}


工具类的代码(可能有点长但都是干货)

package com.oumasoft.art.manage.client.business;

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.CharSet;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import com.linuxense.javadbf.DBFField;
import com.linuxense.javadbf.DBFReader;
import com.linuxense.javadbf.DBFWriter;
import com.oumasoft.art.manage.client.dao.IbatisDAO;
import com.oumasoft.art.manage.client.form.ErrorMsgDTO;

import java.util.regex.Matcher;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;


public class SystemBusiness{

	/**
	 * 获取用户登录的IP
	 * 
	 * @param HttpServletRequest
	 *            request
	 * @return String ip
	 * @算法:
	 */
	public String getIpAddr(HttpServletRequest request) {
		String ip = null;
		ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 将字符串中的换行符替换为html的
* * @param String * srcString 待转换字符串 * @param String * replaceString 替换符 * @return String 转换后字符串 * @算法: */ public String convertEnter(String srcString, String replaceString) throws Exception { String reg = "[\n-\r]"; Pattern p = Pattern.compile(reg); Matcher m; m = p.matcher(srcString); return m.replaceAll(replaceString); } // //获取当前日期 // public String getDateNow() throws Exception{ // String dateString=(String)IbatisDao.getObjectByIbatis("getSysdate_ibatisXML", null); // return dateString.substring(0,10); // } //字符串转日期 public Date getDateFromStr(String strDate) throws Exception{ return DateFormat.getDateInstance().parse(strDate); } //将double数据保留floats位小数,转换成字符串返回 public String convertDouble(double d,int floats){ if(floats==0){ return ""+Math.round(d); } String floatStr="."; for(int i=0;i excelHeadList; /** * 读取Excel文件内容,放入List中,其中第一行为标头,及数据行HashMap的key * @throws Exception */ public List> getExcelContent(String fileString) throws Exception{ this.excelHeadList=new ArrayList(); File file=new File(fileString); if(!file.exists()){ throw new Exception("上传文件名中可能包含无法识别的字符,请参照如下转码后的文件名“"+fileString.substring(1+fileString.lastIndexOf("\\"))+"”,对比源文件名找到特殊字符,进行修改!"); } Workbook workbook=null; try { //都支持直接用流的方式创建workbook 这个地方是关键 //workbook=Workbook.getWorkbook(new ByteArrayInputStream(file.getByteData())); workbook=Workbook.getWorkbook(file); } catch (BiffException e1) { throw new Exception("请检查您的excel文件格式是否正确!\n"+e1+"\n如果确认文件内容无误,可以尝试将数据拷贝至新Excel(类型97-2003(*.xls))中重试导入!"); } catch (IOException e1) { throw new Exception("创建或者获取流出错!\n"+e1); } return this.getExcelContent(workbook); } /** * @throws Exception * 抛出异常 这些异常留给调用的位子处理 zk读取excel */ public List> getExcelContent(Workbook workbook) throws Exception{ List> dataList =new ArrayList>(); Sheet[] sheets=workbook.getSheets(); if(sheets.length<=0){ workbook.close(); throw new Exception("读取excel的出错,页数小于等于0"); } Sheet sheet=workbook.getSheet(0);//读取到第一页 if(sheet==null){ workbook.close(); throw new Exception("读取excel的出错,sheet 为空"); } int rownum=sheet.getRows();//查看excel的行数 如果行数小于=0表示没有数据 如果页数小于1表实只有表头 都不读 if(rownum<=0){ workbook.close(); throw new Exception("导入的文件为空值"); }else if(rownum==1){ workbook.close(); throw new Exception("导入的文件只有表头"); } int colnum=sheet.getColumns();//列数 Cell[] cbiaot=sheet.getRow(0);//表头 for(int i=0;i rowMap=new HashMap(); Cell[] dd = new Cell[colnum]; Cell[] ddTmp = sheet.getRow(i); if(ddTmp==null||ddTmp.length==0||"".equals(ddTmp[0].getContents())){ break; //遇到空行读取数据结束 } if(dd.length==ddTmp.length){ dd=ddTmp; }else{ if(ddTmp.length * @return * @throws Exception */ public List getExcelHeadList() throws Exception{ if(this.excelHeadList==null||this.excelHeadList.size()<=0){ throw new Exception("读取Excel失败!无法获取表头信息!"); } return excelHeadList; } /** * 判断是否存在中文字符 * @param str * @return */ public boolean isChs(String str) { boolean mark = false; Pattern pattern = Pattern.compile("[\u4E00-\u9FA5]"); Matcher matc = pattern.matcher(str); StringBuffer stb = new StringBuffer(); while (matc.find()) { mark = true; stb.append(matc.group()); } return mark; } /** * 删除某路径下包含某序列名的多个文件 * @param dir * @param fileName * @throws Exception */ public void deleteMutiFileInDir(String dir,String fileNameFilter) throws Exception { File fileDir=new File(dir); if(fileDir.isDirectory()){ File[] fileList=fileDir.listFiles(); for(int i=0;i=0){ try{ fl.delete(); }catch(Exception e){ throw new Exception("删除原先生成的旧数据时发生异常!\n"+e); } i --; } } } } } /** * 新建项目对象单元格 * @param id int id * @param idFrom int id来源 0项目代码表 1上级项目代码表 * @param xmmc String 项目名称 * @param sxh int 顺序号(如果是上级,则为下级项目的最小顺序号) * @param maxSxh int 下级项目的最大顺序号 * @param sjxmdm int 上级项目代码(没有上级则为0) * @param hjbz int 合计标志 * @param colSpan int 列合并 * @param colSpan int 列合并 * @return JSONObject 单元格数据对象 * yh.li@2015-04-15 */ private JSONObject newXmObjCell(int id,int idFrom,String xmmc,int sxh,int maxSxh,int sjxmdm,int hjbz,int colSpan,int rowSpan){ JSONObject obj=new JSONObject(); obj.put("id", id); obj.put("idFrom", idFrom); obj.put("xmmc", xmmc); obj.put("sxh", sxh); obj.put("maxSxh", maxSxh); obj.put("sjxmdm", sjxmdm); obj.put("hjbz", hjbz); obj.put("colSpan", colSpan); obj.put("rowSpan", rowSpan); return obj; } /** * 从服务器某地址下载文件 * @param response HttpServletResponse * @param fileLoc String 文件所在位置 绝对路径+文件名+后缀 * @param fileName String 保存文件显示的文件名+后缀 * yh.li@2015-04-22 * @算法:来自网上,进行参数传递的改造 */ public void downloadFile(HttpServletResponse response,String fileLoc,String fileName) throws Exception{ response.reset();//可以加也可以不加 response.setContentType("application/x-download"); String filedisplay = URLEncoder.encode(fileName,"UTF-8"); //"给用户提供的下载文件名"; response.addHeader("Content-Disposition","attachment;filename=" + filedisplay); java.io.OutputStream outp = null; java.io.FileInputStream in = null; try { outp = response.getOutputStream(); in = new FileInputStream(fileLoc); byte[] b = new byte[1024]; int i = 0; while((i = in.read(b)) > 0) { outp.write(b, 0, i); } // outp.flush(); //要加以下两句话,否则会报错 //java.lang.IllegalStateException: getOutputStream() has already been called for //this response // out.clear(); // out = pageContext.pushBody(); } catch(Exception e) { throw e; } finally { if(in != null) { in.close(); in = null; } //这里不能关闭 //if(outp != null) //{ //outp.close(); //outp = null; //} } } /** * @描述:导出DBF文件 @param List dbfColList=new ArrayList(); //dbf字段名 @param List dbfColMeanList=new ArrayList(); //dbf字段含义 @param List dbfColTypeList=new ArrayList(); //dbf字段类型 @param List dbfColLenList=new ArrayList(); //dbf字段长度 * @param sql 检索数据的sql语句 * @return String 返回的信息 * @作者: * @创建日期: */ public String writeDbf(String dbfFilePath,List dbfColList,List dbfColMeanList,List dbfColTypeList,List dbfColLenList, List> dataList) { String retMsg = null; // 参数判空 if ("".equals(dbfFilePath) || dbfFilePath == null) { return "导出文件路径错误!"; } if (dbfColList.size()==0) { return "导出dbf字段列表为空!"; } if (dbfColList.size() != dbfColMeanList.size() ||dbfColList.size() != dbfColTypeList.size() ||dbfColList.size() != dbfColLenList.size()) { return "导出dbf各属性列表长度不一致!"; } DBFWriter writer = new DBFWriter(); FileOutputStream fos = null; try { // 获得数据库内字段个数 int columncount = dbfColList.size(); DBFField fields[]=new DBFField[columncount]; for (int i = 0; i < columncount; i++) { fields[i] = new DBFField(); fields[i].setName(dbfColList.get(i)); if("c".equals(dbfColTypeList.get(i).toLowerCase())){ fields[i].setDataType(DBFField.FIELD_TYPE_C); fields[i].setFieldLength(dbfColLenList.get(i)); }else if("d".equals(dbfColTypeList.get(i).toLowerCase())){ fields[i].setDataType(DBFField.FIELD_TYPE_N); fields[i].setFieldLength(12); fields[i].setDecimalCount(dbfColLenList.get(i)); }else{ return "不支持的列类型定义"+dbfColTypeList.get(i)+"!"; } } // 把字段信息写入DBFWriter实例,即定义表结构 writer.setFields(fields); writer.setCharactersetName("gbk"); // 获取数据库表中的记录条数 int num = dataList.size();// 获取数据量 // 定义一个对象数组,用于存放从数据库取出的每一条记录 for (int i = 0; i < num; i++) { Object[] rowData = new Object[columncount]; HashMap map = dataList.get(i); for (int j = 0; j < columncount; j++) { // 转型 String input = null; // 如果获取的字段不为空 则把数据内容写入rowData Object data=map.get(dbfColList.get(j).toUpperCase()); if(data==null){ data=map.get(dbfColList.get(j).toLowerCase()); } if (data != null) { // input = (String) map.get(dbfColList.get(j).toUpperCase()); if(dbfColTypeList.get(j).toLowerCase().equals("c")){ input = data.toString(); byte[] bs = input.getBytes(); data = new String(bs, "gbk"); }else{ double dataD = Double.parseDouble(data.toString()); // if(Math.ceil(dataD)==dataD){ // data=(int)dataD; // }else{ // data=dataD; // } data=dataD; } rowData[j] = data; } else { rowData[j] = null; } } // 把数据写入dbfWriter writer.addRecord(rowData); } // 定义输出流,并关联的一个文件 fos = new FileOutputStream(dbfFilePath); // 写入数据 writer.write(fos); } catch (Exception e) { retMsg = "从数据库中导出" + dbfFilePath + "时出现异常:" + e.getMessage(); e.printStackTrace(); return retMsg; } finally { try { fos.close(); } catch (Exception e) { // retMsg += "关闭输出连接时出现异常:" + e.getMessage(); return retMsg; } } return retMsg; } /** * 获取临时文件存储所在的目录 * @param HttpServletRequest request * @return String 路径 * @算法: */ public String getFileTempDir(HttpServletRequest request) throws Exception{ String dir=request.getSession().getServletContext().getRealPath("临时文件"); new File(dir).mkdirs(); return dir; } /** * 新建txt,写入内容 * @param txtFile txt文件绝对路径+文件名 * @param textList 写入内容,逐行写入 */ public boolean writerTxt(String txtFile,List textList) { BufferedWriter fw = null; try { File file = new File(txtFile); boolean lb_ret=true; if(file.exists()){ lb_ret=file.delete(); } if(lb_ret){ fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8")); // 指定编码格式,以免读取时中文字符异常 for(int i=0;i fileList) throws Exception { FileOutputStream fos = null; ZipOutputStream zos = null; try { fos = new FileOutputStream(zipPath); zos = new ZipOutputStream(fos); zos.setEncoding("gbk"); this.writeZip(zos,fileList); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { try { if (zos != null) { zos.close(); } } catch (IOException e) { e.printStackTrace(); } } } private void writeZip(ZipOutputStream zos,List fileList) throws SQLException { for(int i = 0; i < fileList.size(); i++){ String filePath=fileList.get(i); File file = new File(fileList.get(i)); if(file.exists()){ FileInputStream fis=null; DataInputStream dis=null; try { fis=new FileInputStream(file); dis=new DataInputStream(new BufferedInputStream(fis)); ZipEntry ze = new ZipEntry(file.getName()); zos.putNextEntry(ze); byte [] content=new byte[8192]; int len; while((len=fis.read(content))!=-1){ zos.write(content,0,len); zos.flush(); } } catch (FileNotFoundException e) { } catch (IOException e) { }finally{ try { if(dis!=null){ dis.close(); } }catch(IOException e){ e.printStackTrace(); } } } } } }

你可能感兴趣的:(后端,实用工具,Java,java)