资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

java表格导出代码 java的excel导出

java里将从excel读到的数据用csv导出,代码怎么写

解释:csv文件实际上就是字符串,之间用“,”进行分割,之后进行的存储。

站在用户的角度思考问题,与客户深入沟通,找到白云网站设计与白云网站推广的解决方案,凭借多年的经验,让设计与互联网技术结合,创造个性化、用户体验好的作品,建站类型包括:网站制作、做网站、企业官网、英文网站、手机端网站、网站推广、域名注册、虚拟空间、企业邮箱。业务覆盖白云地区。

工具类如下:

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStreamWriter;

import java.util.List;

/**

*

* CSV文件导出工具类

*/

public class CSVUtils {

/**

* CSV文件生成方法

* @param head

* @param dataList

* @param outPutPath

* @param filename

* @return

*/

public static File createCSVFile(List head, ListList dataList,

String outPutPath, String filename) {

File csvFile = null;

BufferedWriter csvWtriter = null;

try {

csvFile = new File(outPutPath + File.separator + filename + ".csv");

File parent = csvFile.getParentFile();

if (parent != null !parent.exists()) {

parent.mkdirs();

}

csvFile.createNewFile();

// GB2312使正确读取分隔符","

csvWtriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(

csvFile), "GB2312"), 1024);

// 写入文件头部

writeRow(head, csvWtriter);

// 写入文件内容

for (List row : dataList) {

writeRow(row, csvWtriter);

}

csvWtriter.flush();

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

csvWtriter.close();

} catch (IOException e) {

e.printStackTrace();

}

}

return csvFile;

}

/**

* 写一行数据方法

* @param row

* @param csvWriter

* @throws IOException

*/

private static void writeRow(List row, BufferedWriter csvWriter) throws IOException {

// 写入文件头部

for (Object data : row) {

StringBuffer sb = new StringBuffer();

String rowStr = sb.append("\"").append(data).append("\",").toString();

csvWriter.write(rowStr);

}

csvWriter.newLine();

}

}

Object-Z

java导出excel

java导出Excel

java 代码 /* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */ package com.axon.fable.sams.view.action; import java.io.IOException; import java.io.OutputStream; import java.util.List; import javax.serv ...

java导出Excel例举方式

方法一:导出Excel数据的插件jexcelapi

程序实例如下:

public void exportClassroom(OutputStream os) throws PaikeException {

try {

WritableWorkbook wbook = Workbook.createWorkbook(os); //建立excel文件

WritableSheet wsheet = wbook.createSheet("教室信息表", 0); //工作表名称

//设置Excel字体

WritableFont wfont = new WritableFont(WritableFont.ARIAL, 16,

WritableFont.BOLD, false,

jxl.format.UnderlineStyle.NO_UNDERLINE,

jxl.format.Colour.BLACK);

WritableCellFormat titleFormat = new WritableCellFormat(wfont);

String[] title = { "教室名", "容 量", "类 型", "其他说明" };

//设置Excel表头

for (int i = 0; i title.length; i++) {

Label excelTitle = new Label(i, 0, title[i], titleFormat);

wsheet.addCell(excelTitle);

}

int c = 1; //用于循环时Excel的行号

ClassroomService cs = new ClassroomService();

List list = cs.findAllClassroom(); //这个是从数据库中取得要导出的数据

Iterator it = list.iterator();

while (it.hasNext()) {

ClassroomDTO crdto = (ClassroomDTO) it.next();

Label content1 = new Label(0, c, crdto.getRoomname());

Label content2 = new Label(1, c, crdto.getCapicity().toString());

Label content3 = new Label(2, c, crdto.getRoomTypeId()

.toString());

Label content4 = new Label(3, c, crdto.getRemark());

wsheet.addCell(content1);

wsheet.addCell(content2);

wsheet.addCell(content3);

wsheet.addCell(content4);

c++;

}

wbook.write(); //写入文件

wbook.close();

os.close();

} catch (Exception e) {

throw new PaikeException("导出文件出错");

}

}

方法二:直接用Java代码实现导出Excel报表

/*

* Generated by MyEclipse Struts

* Template path: templates/java/JavaClass.vtl

*/

package com.axon.fable.sams.view.action;

import java.io.IOException;

import java.io.OutputStream;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;

import jxl.write.WriteException;

import jxl.write.biff.RowsExceededException;

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionForward;

import org.apache.struts.action.ActionMapping;

import org.hibernate.HibernateException;

import org.hibernate.Query;

import org.hibernate.Session;

import org.hibernate.Transaction;

import com.axon.fable.empolderpackage.out.OutJavaScript;

import com.axon.fable.empolderpackage.page.Pager;

import com.axon.fable.empolderpackage.string.MyPublic;

import com.axon.fable.sams.common.BaseAction;

import com.axon.fable.sams.exception.AppBusinessException;

import com.axon.fable.sams.exception.AppSystemException;

/**

* MyEclipse Struts

* Creation date: 06-28-2007

*

* XDoclet definition:

* @struts.action path="/axon" name="axonForm" input="/samspage/zm/axon.jsp" parameter="method" scope="request" validate="true"

* @struts.action-forward name="success" path="/samspage/zm/content.jsp"

*/

public class StshipoperationAction extends BaseAction {

/*

* Generated Methods

*/

private static Session session=null;

private static Transaction ts=null;

private static Query queryC=null;

private static Query queryR=null;

private static Query query=null;

private static List list=null;

private static Integer startRow;

private static Integer ncurrentPage;

private static Integer cell;

private static String property;

private static String sql;

private static String type;

private static String condition ;//是否导出当前页

private static String currentPage;

private static String from ;

private static String pactdata;

private static String voyagename;

private static String voyageno;

private static String dwt ;

private static String hirefrom ;

private static String deliveryposion ;

private static String redeliveryposion ;

private static String sheepowner ;

private static String addr;

private static String addcomm;

private static String rent;

private static String fileName ;

private static OutputStream os;

@Override

public ActionForward findAll(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {

// TODO Auto-generated method stub

return null;

}

@Override

public ActionForward findById(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {

// TODO Auto-generated method stub

return null;

}

@Override

public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {

// TODO Auto-generated method stub

return null;

}

public static String strNull(Object nullStr,String newStr,Integer cell){

if(nullStr==null||nullStr.equals("")){return newStr;}else{cell+=1;return nullStr+"";}

}

public static String getStr(String str,Integer cell){

if(str==null||str.trim().equals("")){return "";}else{cell+=1;return ","+str;}

}

public static String getExcelTile(String title){

if(title==null)

return "";

if(title.equals("modela.stsid"))

return "编号";

if(title.equals("modelc.pactdata"))

return "合同日期";

if(title.equals("modela.voyagename"))

return "航名";

if(title.equals("modela.voyageno"))

return "航次";

if(title.equals("modelc.dwt"))

return "DWT";

if(title.equals("modelc.hirefrom"))

return "受载期";

if(title.equals("modela.deliveryposion"))

return "交船地点";

if(title.equals("modela.redeliveryposion"))

return "还船地点";

if(title.equals("modelc.sheepowner"))

return "联系人";

if(title.equals("modelc.addr"))

return "经纪人拥金";

if(title.equals("modelc.addcomm"))

return "ADD COMM";

if(title.equals("modelc.rent"))

return "租金";

return "";

}

public ActionForward exporVoyagesInfoToExcel(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) {

list=null;

startRow=0;

ncurrentPage=1;

cell=0;

type =request.getParameter("type");

condition =request.getParameter("condition");//是否导出当前页

currentPage =request.getParameter("currentPage");

from =request.getParameter("from");

pactdata = request.getParameter("modelc.pactdata");

voyagename = request.getParameter("modela.voyagename");

voyageno = request.getParameter("modela.voyageno");

dwt = request.getParameter("modelc.dwt");

hirefrom = request.getParameter("modelc.hirefrom");

deliveryposion = request.getParameter("modela.deliveryposion");

redeliveryposion = request.getParameter("modela.redeliveryposion");

sheepowner = request.getParameter("modelc.sheepowner");

addr = request.getParameter("modelc.addr");

addcomm = request.getParameter("modelc.addcomm");

rent = request.getParameter("modelc.rent");

if(type!=nulltype.trim().equals("1")){

type ="已还船舶--费用未结清";

}else{

type ="已还船舶--费用已结清";

}

property =getStr(pactdata,cell)+getStr(voyagename,cell)+getStr(voyageno,cell)+getStr(dwt,cell)+getStr(hirefrom,cell)

+getStr(deliveryposion,cell)+getStr(redeliveryposion,cell)+getStr(sheepowner,cell)+getStr(addr,cell)+getStr(addcomm,cell)

+getStr(rent,cell);

property = property.substring(1);

String split[] = property.split(",");

// System.out.println("-----------------------------property:"+property);

if(currentPage!=null!currentPage.trim().equals("")){

ncurrentPage =Integer.parseInt(currentPage);

}else{

OutJavaScript.outString(response, "Sorry! Failed to get information of pager.");

return null;

}

try {

session =getServiceLocator().getBaseHibernateDAO().getSession();

sql ="select count(*) "+from;

query =session.createQuery(sql);

list = query.list();

for (int i = 0; i list.size(); i++) {

totalSize =(Integer)list.get(i);

if(totalSize!=0){

pager =new Pager(ncurrentPage,totalSize);

}

}

query =getServiceLocator().getBaseHibernateDAO().getSession().createQuery("select " +property+from);

if(condition!=nullcondition.trim().equals("1")){//分页数据

startRow = (ncurrentPage - 1)*pager.getPageSize();

query.setFirstResult(startRow);

query.setMaxResults(pager.getPageSize());

// System.out.println("---------------------------------------------------query:"+query);

}

list = query.list();

fileName = "shipInfo";

os = response.getOutputStream();

response.reset();

response.setHeader("Content-disposition",

"attachment; filename=" +fileName + ".xls");

response.setContentType("application/msexcel");

jxl.write.WritableWorkbook wbook = Workbook.createWorkbook(os);

jxl.write.WritableSheet wsheet = wbook.createSheet("the first sheet", 0);

for (int i = 0; i split.length; i++) {

jxl.write.Label wlabel0;

wlabel0 = new jxl.write.Label(i, 0, getExcelTile(split[i]));

wsheet.addCell(wlabel0);

}

jxl.write.Label wlabel1;

for(int i=0;ilist.size();i++) {

if(split.length==1){

Object strval = (Object) list.get(i);

String javaScript=""+MyPublic.toHtmlStr(strval==null?"":strval.toString().trim())+"";

wlabel1 = new jxl.write.Label(0, i+1,strval==null?"":strval.toString().trim() );

wsheet.addCell(wlabel1);

}else{

Object[] strval = (Object[]) list.get(i);

for(int j=0;jstrval.length;j++) {

String javaScript=""+MyPublic.toHtmlStr(strval[j]==null?"":strval[j].toString().trim())+"";

//System.out.println("===================script:"+javaScript);

wlabel1 = new jxl.write.Label(j, i+1,strval[j]==null?"":strval[j].toString().trim() );

wsheet.addCell(wlabel1);

}

}

}

wbook.write();

response.flushBuffer();

wbook.close();

os.close();

} catch (IOException e) {

// TODO Auto-generated catch block

OutJavaScript.outString(response, "Sorry! Export Excel exception.");

e.printStackTrace();

} catch (HibernateException e1) {

// TODO Auto-generated catch block

OutJavaScript.outString(response, "Sorry! Database exception.");

e1.printStackTrace();

} catch (AppSystemException e1) {

// TODO Auto-generated catch block

OutJavaScript.outString(response, "Sorry! System exception.");

e1.printStackTrace();

} catch (AppBusinessException e1) {

// TODO Auto-generated catch block

OutJavaScript.outString(response, "Sorry! Database exception.");

e1.printStackTrace();

} catch (RowsExceededException e) {

// TODO Auto-generated catch block

OutJavaScript.outString(response, "Sorry! Export Excel exception.");

e.printStackTrace();

} catch (WriteException e) {

// TODO Auto-generated catch block

OutJavaScript.outString(response, "Sorry! Export Excel exception.");

e.printStackTrace();

}

return null;

}

@Override

public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {

// TODO Auto-generated method stub

return null;

}

}

还有其他很多种 字数限制 无法一一举例方式

Java 利用poi 导出excel表格如何在导出时自由选择路径?

导出时自由选择路径的代码如下:

1、后台输出Excel文件代码:

OutputStream output = response.getOutputStream();

response.reset();

response.setHeader("Content-disposition", "attachment; filename=" + path);

response.setContentType("Content-Type:application/vnd.ms-excel ");

wb.write(output);

output.close();

2、前端代码:

window.open("getExcelList","_blank");

导出excel数据

* @param id

* @param m

* @return

*/

@RequestMapping("/exportExcel")

public void exportExcel(@RequestParam("id") Integer id, Model m,HttpServletRequest req, HttpServletResponse resp) {

try {

ExportExcelP2pLoanPlanVo ex = new ExportExcelP2pLoanPlanVo();

String[] headers = {"最迟还款日", "还款金额","剩余几天","逾期几天", "罚息","是否垫付","状态","是否发放收益"};

ListP2pLoanPlanVo dataset = new ArrayListP2pLoanPlanVo();

ListP2pLoanPlan plans = this.planService.getListByLoan(id);

for (int i = 0; i plans.size(); i++) {

P2pLoanPlanVo p2pLoanPlanVo = new P2pLoanPlanVo();

p2pLoanPlanVo.setRepayDate(plans.get(i).getRepayDate());

p2pLoanPlanVo.setRepayAmount(plans.get(i).getRepayAmount());

if(plans.get(i).getRepayDays() = 0 plans.get(i).getStatus() == 0){

p2pLoanPlanVo.setRepayDays(plans.get(i).getRepayDays());

}else{

p2pLoanPlanVo.setRepayDays(0);

}

if(plans.get(i).getRepayDays() 0 plans.get(i).getStatus() == 0){

p2pLoanPlanVo.setRepayYqDays(-plans.get(i).getRepayDays());

}else{

p2pLoanPlanVo.setRepayYqDays(0);

}

java如何导出excel表格,如果用poi,java代码如何实现.,求代码!!!

项目结构:

xls:

\\\

XlsMain .java 类

//该类有main方法,主要负责运行程序,同时该类中也包含了用poi读取Excel(2003版)

*

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.util.ArrayList;

import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;

import org.apache.poi.hssf.usermodel.HSSFRow;

import org.apache.poi.hssf.usermodel.HSSFSheet;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**

*

* @author Hongten/br

*

* 参考地址:

*

*/

public class XlsMain {

public static void main(String[] args) throws IOException {

XlsMain xlsMain = new XlsMain();

XlsDto xls = null;

ListXlsDto list = xlsMain.readXls();

try {

XlsDto2Excel.xlsDto2Excel(list);

} catch (Exception e) {

e.printStackTrace();

}

for (int i = 0; i list.size(); i++) {

xls = (XlsDto) list.get(i);

System.out.println(xls.getXh() + " " + xls.getXm() + " "

+ xls.getYxsmc() + " " + xls.getKcm() + " "

+ xls.getCj());

}

}

/**

* 读取xls文件内容

*

* @return ListXlsDto对象

* @throws IOException

* 输入/输出(i/o)异常

*/

private ListXlsDto readXls() throws IOException {

InputStream is = new FileInputStream("pldrxkxxmb.xls");

HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);

XlsDto xlsDto = null;

ListXlsDto list = new ArrayListXlsDto();

// 循环工作表Sheet

for (int numSheet = 0; numSheet hssfWorkbook.getNumberOfSheets(); numSheet++) {

HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);

if (hssfSheet == null) {

continue;

}

// 循环行Row

for (int rowNum = 1; rowNum = hssfSheet.getLastRowNum(); rowNum++) {

HSSFRow hssfRow = hssfSheet.getRow(rowNum);

if (hssfRow == null) {

continue;

}

xlsDto = new XlsDto();

// 循环列Cell

// 0学号 1姓名 2学院 3课程名 4 成绩

// for (int cellNum = 0; cellNum =4; cellNum++) {

HSSFCell xh = hssfRow.getCell(0);

if (xh == null) {

continue;

}

xlsDto.setXh(getValue(xh));

HSSFCell xm = hssfRow.getCell(1);

if (xm == null) {

continue;

}

xlsDto.setXm(getValue(xm));

HSSFCell yxsmc = hssfRow.getCell(2);

if (yxsmc == null) {

continue;

}

xlsDto.setYxsmc(getValue(yxsmc));

HSSFCell kcm = hssfRow.getCell(3);

if (kcm == null) {

continue;

}

xlsDto.setKcm(getValue(kcm));

HSSFCell cj = hssfRow.getCell(4);

if (cj == null) {

continue;

}

xlsDto.setCj(Float.parseFloat(getValue(cj)));

list.add(xlsDto);

}

}

return list;

}

/**

* 得到Excel表中的值

*

* @param hssfCell

* Excel中的每一个格子

* @return Excel中每一个格子中的值

*/

@SuppressWarnings("static-access")

private String getValue(HSSFCell hssfCell) {

if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {

// 返回布尔类型的值

return String.valueOf(hssfCell.getBooleanCellValue());

} else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {

// 返回数值类型的值

return String.valueOf(hssfCell.getNumericCellValue());

} else {

// 返回字符串类型的值

return String.valueOf(hssfCell.getStringCellValue());

}

}

}

XlsDto2Excel.java类

//该类主要负责向Excel(2003版)中插入数据

import java.io.FileOutputStream;

import java.io.OutputStream;

import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;

import org.apache.poi.hssf.usermodel.HSSFRichTextString;

import org.apache.poi.hssf.usermodel.HSSFRow;

import org.apache.poi.hssf.usermodel.HSSFSheet;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class XlsDto2Excel {

/**

*

* @param xls

* XlsDto实体类的一个对象

* @throws Exception

* 在导入Excel的过程中抛出异常

*/

public static void xlsDto2Excel(ListXlsDto xls) throws Exception {

// 获取总列数

int CountColumnNum = xls.size();

// 创建Excel文档

HSSFWorkbook hwb = new HSSFWorkbook();

XlsDto xlsDto = null;

// sheet 对应一个工作页

HSSFSheet sheet = hwb.createSheet("pldrxkxxmb");

HSSFRow firstrow = sheet.createRow(0); // 下标为0的行开始

HSSFCell[] firstcell = new HSSFCell[CountColumnNum];

String[] names = new String[CountColumnNum];

names[0] = "学号";

names[1] = "姓名";

names[2] = "学院";

names[3] = "课程名";

names[4] = "成绩";

for (int j = 0; j CountColumnNum; j++) {

firstcell[j] = firstrow.createCell(j);

firstcell[j].setCellValue(new HSSFRichTextString(names[j]));

}

for (int i = 0; i xls.size(); i++) {

// 创建一行

HSSFRow row = sheet.createRow(i + 1);

// 得到要插入的每一条记录

xlsDto = xls.get(i);

for (int colu = 0; colu = 4; colu++) {

// 在一行内循环

HSSFCell xh = row.createCell(0);

xh.setCellValue(xlsDto.getXh());

HSSFCell xm = row.createCell(1);

xm.setCellValue(xlsDto.getXm());

HSSFCell yxsmc = row.createCell(2);

yxsmc.setCellValue(xlsDto.getYxsmc());

HSSFCell kcm = row.createCell(3);

kcm.setCellValue(xlsDto.getKcm());

HSSFCell cj = row.createCell(4);

cj.setCellValue(xlsDto.getCj());

(xlsDto.getMessage());

}

}

// 创建文件输出流,准备输出电子表格

OutputStream out = new FileOutputStream("POI2Excel/pldrxkxxmb.xls");

hwb.write(out);

out.close();

System.out.println("数据库导出成功");

}

}

XlsDto .java类

//该类是一个实体类

public class XlsDto {

/**

* 选课号

*/

private Integer xkh;

/**

* 学号

*/

private String xh;

/**

* 姓名

*/

private String xm;

/**

* 学院

*/

private String yxsmc;

/**

* 课程号

*/

private Integer kch;

/**

* 课程名

*/

private String kcm;

/**

* 成绩

*/

private float cj;

public Integer getXkh() {

return xkh;

}

public void setXkh(Integer xkh) {

this.xkh = xkh;

}

public String getXh() {

return xh;

}

public void setXh(String xh) {

this.xh = xh;

}

public String getXm() {

return xm;

}

public void setXm(String xm) {

this.xm = xm;

}

public String getYxsmc() {

return yxsmc;

}

public void setYxsmc(String yxsmc) {

this.yxsmc = yxsmc;

}

public Integer getKch() {

return kch;

}

public void setKch(Integer kch) {

this.kch = kch;

}

public String getKcm() {

return kcm;

}

public void setKcm(String kcm) {

this.kcm = kcm;

}

public float getCj() {

return cj;

}

public void setCj(float cj) {

this.cj = cj;

}

}

后台输出:

数据库导出成功

1.0 hongten 信息技术学院 计算机网络应用基础 80.0

2.0 王五 信息技术学院 计算机网络应用基础 81.0

3.0 李胜基 信息技术学院 计算机网络应用基础 82.0

4.0 五班古 信息技术学院 计算机网络应用基础 83.0

5.0 蔡诗芸 信息技术学院 计算机网络应用基础 84.0


网站栏目:java表格导出代码 java的excel导出
本文路径:http://www.cdkjz.cn/article/hiejsg.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220