package com.ufinity.mealsordering.common.util;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import com.ufinity.mealsordering.common.Config;
import com.ufinity.mealsordering.common.Constant;
import com.ufinity.mealsordering.dao.impl.BaseDAO;

public class CreateCSVFile extends BaseDAO...{
private static CreateCSVFile _createCSVFile = null;
private FileOutputStream _fos = null;
private StringBuffer _sBuffer = null;
private String _path = "";
public static final String DEL_CHAR = ",";
public static final String AV_CHAR = """;

public CreateCSVFile() ...{
_path = Config.getString("csv_file_path");
this.init(_path);
}

/** *//**
*
* @param path create csv file's path
*/ 
public void init(String path) ...{
String method = "createCSVFile_init";

if(path == null || path.trim().equals("")) ...{
_path = Constant.DEFAULT_PATH; 
} else ...{
_path = path;
} 
try ...{
_fos = new FileOutputStream(_path,false);
_sBuffer = new StringBuffer();
debug("", method, "create csv file sccuessful"); 
} catch (FileNotFoundException e) ...{
e.printStackTrace();
debug("", method, "not found exception of create csv file");
}
}

/** *//**
* this method is append date in csv file
* @param data
*/ 
public void setData(Object data) ...{
_sBuffer.append(AV_CHAR);
_sBuffer.append(data);
_sBuffer.append(AV_CHAR);
_sBuffer.append(DEL_CHAR);
}

public void writeLine() ...{
if (_sBuffer.charAt(_sBuffer.length() - 1) == ',')
_sBuffer.delete(_sBuffer.length() - 1, _sBuffer.length());
_sBuffer.append(" ");
}

/** *//**
* this method is close fileoutputstream
*/ 
public void close() ...{
String method = "close"; 
try ...{ 
if(_sBuffer != null) ...{
_fos.write(_sBuffer.toString().getBytes());
debug("", method, "close fileOutputStream successful"); 
} else ...{
debug("", method, "null point exception");
} 
} catch (IOException e) ...{
debug("", method, "close fileOutputStream failure"); 
} finally ...{ 
try ...{ 
if(_fos != null) ...{
_fos.close();
_fos = null;
} 
} catch (IOException e) ...{
e.printStackTrace();
}
}
}
} 
package com.ufinity.mealsordering.common.util;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import com.ufinity.mealsordering.common.Config;
import com.ufinity.mealsordering.common.Constant;
import com.ufinity.mealsordering.dao.impl.BaseDAO;

public class CreateCSVFile extends BaseDAO...{
private static CreateCSVFile _createCSVFile = null;
private FileOutputStream _fos = null;
private StringBuffer _sBuffer = null;
private String _path = "";
public static final String DEL_CHAR = ",";
public static final String AV_CHAR = """;

public CreateCSVFile() ...{
_path = Config.getString("csv_file_path");
this.init(_path);
}

/** *//**
*
* @param path create csv file's path
*/
public void init(String path) ...{
String method = "createCSVFile_init";

if(path == null || path.trim().equals("")) ...{
_path = Constant.DEFAULT_PATH;
} else ...{
_path = path;
}
try ...{
_fos = new FileOutputStream(_path,false);
_sBuffer = new StringBuffer();
debug("", method, "create csv file sccuessful");
} catch (FileNotFoundException e) ...{
e.printStackTrace();
debug("", method, "not found exception of create csv file");
}
}

/** *//**
* this method is append date in csv file
* @param data
*/
public void setData(Object data) ...{
_sBuffer.append(AV_CHAR);
_sBuffer.append(data);
_sBuffer.append(AV_CHAR);
_sBuffer.append(DEL_CHAR);
}

public void writeLine() ...{
if (_sBuffer.charAt(_sBuffer.length() - 1) == ',')
_sBuffer.delete(_sBuffer.length() - 1, _sBuffer.length());
_sBuffer.append(" ");
}

/** *//**
* this method is close fileoutputstream
*/
public void close() ...{
String method = "close";
try ...{
if(_sBuffer != null) ...{
_fos.write(_sBuffer.toString().getBytes());
debug("", method, "close fileOutputStream successful");
} else ...{
debug("", method, "null point exception");
}
} catch (IOException e) ...{
debug("", method, "close fileOutputStream failure");
} finally ...{
try ...{
if(_fos != null) ...{
_fos.close();
_fos = null;
}
} catch (IOException e) ...{
e.printStackTrace();
}
}
}
}

2.Create CSV File Action:
Java代码 
/** *//**
* updateExpired method is update order_history table's attribute(is
* expired) Expired that the <True> value is 0, 1 said that <False>
*
* @param mapping
* @param form
* @param request
* @param response
* @author wuwenqiang
*/
public ActionForward updateExpired(ActionMapping mapping, ActionForm form, 
HttpServletRequest request, HttpServletResponse response) ...{
String method = "updateExpired";
String createFileMethod = "createFile";
String userId = (String) request.getSession().getAttribute("Portal");
ActionMapping _mapping = null;
List allOrderHistoryList = new LinkedList();
List _orderHistoryList = new LinkedList();

try ...{
DateManager.getInstance().compareTime(_am.queryALlGlobalSettings());
long startTime = DateManager.getInstance().get_timeMillisStart();
long endTime = DateManager.getInstance().get_timeMillisEnd();
allOrderHistoryList = _am.queryOrderHistoryAll(startTime, endTime); 
if (allOrderHistoryList == null || allOrderHistoryList.size() <= 0) ...{
this.debug(userId, createFileMethod,
Constant.MESSAGE_QUERY_NOELEMENT); 
} else ...{
_orderHistoryList = _ohOperation
.addOrderHistory(allOrderHistoryList);
CreateCSVFile createCSVFile = new CreateCSVFile();
createCSVFile.setData(Constant.RESTAURANT_NAME);
createCSVFile.setData(Constant.MEAL_NAME);
createCSVFile.setData(Constant.MEAL_PRICE);
createCSVFile.setData(Constant.NUM);
createCSVFile.setData(Constant.SUBSCRIBER_NAME);
createCSVFile.setData(Constant.ORDER_TIME);
createCSVFile.writeLine(); 
for (int i = 0; i < allOrderHistoryList.size(); i++) ...{
OrderHistory orderHistory = (OrderHistory) allOrderHistoryList
.get(i);
createCSVFile.setData(orderHistory.getMeal()
.getRestaurant().getRestName());
createCSVFile.setData(orderHistory.getMeal().getMealName());
createCSVFile.setData(orderHistory.getMeal()
.getSinglePrice());
createCSVFile.setData(orderHistory.getNum());
createCSVFile.setData(orderHistory.getEmployee()
.getFullName());
createCSVFile.setData(orderHistory.getTime());
createCSVFile.writeLine();
}
createCSVFile.close();
} _am.updateExpired(startTime, endTime);
request.getSession().setAttribute("addOrderHistory_list",_orderHistoryList);
request.setAttribute("flag", "flag_true");
this.debug(userId, method, Constant.LOG_UPDATE_SUCCESS);
return mapping.findForward("list_update");

} catch (ManagerException e) ...{
e.printStackTrace();
this.error(userId, method, "hibernate exception", e);
}
this.debug(userId, method, Constant.LOG_UPDATE_FAIL);
request.setAttribute("flag", "flag_false");
return mapping.findForward("return_error");
} 

/** *//**
* updateExpired method is update order_history table's attribute(is
* expired) Expired that the <True> value is 0, 1 said that <False>
*
* @param mapping
* @param form
* @param request
* @param response
* @author wuwenqiang
*/
public ActionForward updateExpired(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) ...{
String method = "updateExpired";
String createFileMethod = "createFile";
String userId = (String) request.getSession().getAttribute("Portal");
ActionMapping _mapping = null;
List allOrderHistoryList = new LinkedList();
List _orderHistoryList = new LinkedList();

try ...{
DateManager.getInstance().compareTime(_am.queryALlGlobalSettings());
long startTime = DateManager.getInstance().get_timeMillisStart();
long endTime = DateManager.getInstance().get_timeMillisEnd();
allOrderHistoryList = _am.queryOrderHistoryAll(startTime, endTime);
if (allOrderHistoryList == null || allOrderHistoryList.size() <= 0) ...{
this.debug(userId, createFileMethod,
Constant.MESSAGE_QUERY_NOELEMENT);
} else ...{
_orderHistoryList = _ohOperation
.addOrderHistory(allOrderHistoryList);
CreateCSVFile createCSVFile = new CreateCSVFile();
createCSVFile.setData(Constant.RESTAURANT_NAME);
createCSVFile.setData(Constant.MEAL_NAME);
createCSVFile.setData(Constant.MEAL_PRICE);
createCSVFile.setData(Constant.NUM);
createCSVFile.setData(Constant.SUBSCRIBER_NAME);
createCSVFile.setData(Constant.ORDER_TIME);
createCSVFile.writeLine();
for (int i = 0; i < allOrderHistoryList.size(); i++) ...{
OrderHistory orderHistory = (OrderHistory) allOrderHistoryList
.get(i);
createCSVFile.setData(orderHistory.getMeal()
.getRestaurant().getRestName());
createCSVFile.setData(orderHistory.getMeal().getMealName());
createCSVFile.setData(orderHistory.getMeal()
.getSinglePrice());
createCSVFile.setData(orderHistory.getNum());
createCSVFile.setData(orderHistory.getEmployee()
.getFullName());
createCSVFile.setData(orderHistory.getTime());
createCSVFile.writeLine();
}
createCSVFile.close();
} _am.updateExpired(startTime, endTime);
request.getSession().setAttribute("addOrderHistory_list",_orderHistoryList);
request.setAttribute("flag", "flag_true");
this.debug(userId, method, Constant.LOG_UPDATE_SUCCESS);
return mapping.findForward("list_update");

} catch (ManagerException e) ...{
e.printStackTrace();
this.error(userId, method, "hibernate exception", e);
}
this.debug(userId, method, Constant.LOG_UPDATE_FAIL);
request.setAttribute("flag", "flag_false");
return mapping.findForward("return_error");
}


3.DownLoad CSV File Action:
Java代码 
/** *//**
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws UnsupportedEncodingException
*/
public ActionForward downloadCSVFile(ActionMapping mapping,
ActionForm form, HttpServletRequest request, 
HttpServletResponse response) ...{
String method = "downloadCSVFile";
String userId = (String) request.getSession().getAttribute("Portal");
PrintWriter pw = null;
response.setContentType("application/octet-stream;charset=GBK");
response.setHeader("Content-Disposition",
"attachment; filename="mealordering.csv"");
List allOrderHistoryList = new LinkedList();
String strHead = Constant.RESTAURANT_NAME + "," + Constant.MEAL_NAME
+ "," + Constant.MEAL_PRICE + "," + Constant.NUM + ","
+ Constant.SUBSCRIBER_NAME + "," + Constant.ORDER_TIME;

try ...{
pw = response.getWriter();
pw.println(strHead);
allOrderHistoryList = (List)request.getSession().getAttribute("addOrderHistory_list");

if (allOrderHistoryList == null || allOrderHistoryList.size() <= 0) ...{
this.debug("'", method, Constant.MESSAGE_QUERY_NOELEMENT);

} else ...{
for (Iterator iterator = allOrderHistoryList.iterator(); iterator 
.hasNext();) ...{
OrderHistory orderHistory = (OrderHistory) iterator.next();
String restName = String.valueOf(orderHistory.getMeal()
.getRestaurant().getRestName());
String mealName = String.valueOf(orderHistory.getMeal()
.getMealName());
String mealPrice = String.valueOf(orderHistory.getMeal()
.getSinglePrice());
String num = String.valueOf(orderHistory.getNum());
String subscriber = String.valueOf(orderHistory
.getEmployee().getFullName());
String orderTime = String.valueOf(orderHistory.getTime());
String strLine = """ + restName + "","" + mealName
+ "","" + mealPrice + "","" + num + "",""
+ subscriber + "","" + orderTime + """;
pw.println(strLine);
}
pw.flush();
pw.close();
} 
} catch (IOException e) ...{
e.printStackTrace();
this.debug(userId, method, "IOException");
}
return null;
} 
本文介绍了一种Java实现的CSV文件生成方法,并详细展示了如何将数据库查询结果写入CSV文件,最后实现了CSV文件的下载功能。文章还包含了完整的代码示例。
2155

被折叠的 条评论
为什么被折叠?



