当前位置:首页 » 数据仓库 » poi数据库导出excel文件
扩展阅读
webinf下怎么引入js 2023-08-31 21:54:13
堡垒机怎么打开web 2023-08-31 21:54:11

poi数据库导出excel文件

发布时间: 2022-05-02 13:50:20

A. java用poi实现将数据库里面的数据导入已经存在的excel模板中。最好有实例参考,谢谢。

/**
*通过EXCEL模板导入团队信息
*/
@ResponseBody
@RequestMapping("importTemp")
publicMap<String,String>importTemp(HttpServletRequestrequest,HttpSessionsession,
@RequestParam(value="excel",required=false)MultipartFilefile,HttpServletResponseresponse){
Yhbyhb=(Yhb)session.getAttribute(WebConstants.CURRENT_USER);
Stringzjr=yhb.getYhid();
List<DrTdb>tdxxList=newArrayList<DrTdb>();
Map<String,String>map=newHashMap<String,String>();
Stringsfcg="1";
Stringbcghs="";
Stringbcgyy="";
HSSFWorkbookworkbook=null;
try{
workbook=newHSSFWorkbook(file.getInputStream());
HSSFSheetsheet=workbook.getSheetAt(0);
if(sheet!=null)
{
intd=sheet.getPhysicalNumberOfRows();
other:for(inti=7;i<sheet.getPhysicalNumberOfRows();i++)
{
sfcg="2";
HSSFRowrow=sheet.getRow(i);
DrTdbtd=newDrTdb();
intrs=1;
//td.setTdbm("T"+DateUtil.CurrentTime("MM-dd"));
td.setZjr(zjr);
for(intj=0;j<8;j++)
{
HSSFCellcell=row.getCell(j);
if(j==0){
if(cell!=null){
StringcellStr=cell.toString();
if(isDigit(cellStr)!=""){
StringNDID=(String)tdglService.queryForObject("tdExcel.queryNd",isDigit(cellStr));
td.setNd(NDID);
}else{
sfcg="0";
bcghs=String.valueOf(i+1);
bcgyy="请填写正确的年度";
breakother;
}
}else{
sfcg="0";
bcghs=String.valueOf(i+1);
bcgyy="年度不可为空";
breakother;
}
}elseif(j==1){
if(cell!=null){
StringcellStr=cell.toString();
StringYXID=(String)tdglService.queryForObject("tdExcel.queryIdByYx",cellStr);
StringYXDM=(String)tdglService.queryForObject("tdExcel.queryDmByYx",cellStr);
if(YXDM==null||YXDM==""){
sfcg="0";
bcghs=String.valueOf(i+1);
bcgyy="院系不存在";
breakother;
}
td.setSsyx(YXID);
//设置团队编码
StringcurrentYear=DateUtil.CurrentTime("yyyy");//当前年份
Stringtdbm="";
Stringstr=null;
str="T"+currentYear+YXDM;
StringmaxID=(String)tdglService.queryForObject("tdgl.queryMaxID",str);//当前团队最大ID
Stringstr_q=maxID.substring(1);
intMAXID=Integer.parseInt(str_q);//将返回的字符串去掉T
tdbm="T"+(MAXID+1);
td.setTdbm(tdbm);
}else{
sfcg="0";
bcghs=String.valueOf(i+1);
bcgyy="院系不存在";
breakother;
}
}elseif(j==3){
if(cell!=null){
StringcellStr=cell.toString();
String[]zdjs=cellStr.split(",");
for(intin=0;in<zdjs.length;in++){
zdjs[in]=zdjs[in].substring(1,zdjs[in].length()-1);
//zdjs[in]=isDigit(zdjs[in]);
zdjs[in]=(String)tdglService.queryForObject("tdExcel.queryIdByZgh",zdjs[in]);
if("".equals(zdjs[in])||zdjs[in]==null){
sfcg="0";
bcghs=String.valueOf(i+1);
bcgyy="教师编号有误";
breakother;
}
}
td.setZdjs(zdjs);
}else{
sfcg="0";
bcghs=String.valueOf(i+1);
bcgyy="指导教师不可为空";
breakother;
}
}elseif(j==5){
if(cell!=null){
StringcellStr=cell.toString();
cellStr=cellStr.substring(1,cellStr.length()-1);
//BigDecimalbg=newBigDecimal(cellStr);
//cellStr=bg.toPlainString();
cellStr=(String)tdglService.queryForObject("tdExcel.queryIdByXh",cellStr);

if("".equals(cellStr)||cellStr==null){
sfcg="0";
bcghs=String.valueOf(i+1);
bcgyy="团队组长学号有误";
breakother;
}
else{
StringTdid=(String)tdglService.queryForObject("tdExcel.queryryid",cellStr);
StringXM=(String)tdglService.queryForObject("tdExcel.queryXmBy",cellStr);
if(Tdid!=null){
sfcg="0";
bcghs=String.valueOf(i+1);
bcgyy="团队组长"+XM+"已存在";
breakother;
}
}
td.setTdzz(cellStr);
}else{
sfcg="0";
bcghs=String.valueOf(i+1);
bcgyy="团队组长不可为空";
breakother;
}
}elseif(j==7){
if(cell!=null){
StringcellStr=cell.toString();
String[]tdzy=cellStr.split(",");
for(intk=0;k<tdzy.length;k++){
tdzy[k]=tdzy[k].substring(1,tdzy[k].length()-1);
tdzy[k]=(String)tdglService.queryForObject("tdExcel.queryIdByXh",tdzy[k]);
if("".equals(tdzy[k])||tdzy[k]==null){
sfcg="0";
bcghs=String.valueOf(i+1);
bcgyy="团队组员学号有误";
breakother;
}
rs++;
}
td.setTdzy(tdzy);
}else{
sfcg="0";
bcghs=String.valueOf(i+1);
bcgyy="团队组员不可为空";
breakother;
}
}
}
td.setRs(String.valueOf(rs));
tdxxList.add(td);
}
}
}catch(IOExceptione){
e.printStackTrace();
}
if("2".equals(sfcg)){


for(DrTdbtdxx:tdxxList){
tdglService.insert("tdExcel.addTdxx",tdxx);
tdglService.insert("tdExcel.addTdzz",tdxx);
tdglService.insert("tdExcel.addTdzy",tdxx);
tdglService.insert("tdExcel.addZdjs",tdxx);
}

}
map.put("sfcg",sfcg);
map.put("bcghs",bcghs);
map.put("bcgyy",bcgyy);
returnmap;
}

看不懂留言

B. java用poi导出excel文件,打开导出的文件时报错,怎么办

两个原因:

1.你的excel模版本身有问题,可以尝试新建一个模版。

2.你的excel使用了一些POI不支持的函数。

解决办法:

另存是由excel重写了完整的文件,可以解决问题。

关闭文件例子:

FileOutputStream os = new FileOutputStream("workbook.xls");

wb.write(os);

os.close();

C. 如何将数据库中的数据导出到excel

以下都只是介绍操作的原理,具体要求要在应用中具体分析改变。
1. 此方法常用在form或者Console Application中,使用时须用要添加Reference,具体做法:
右键点击项目添加“Add Reference”,在Tom组件下,选择“Microsoft Excel 14.0 Object Library”,然后在项目中使用
下面注释//it looks like excele table start with 1 not 1
应该为//it looks like excele table start with 1 not 0

[csharp] view plain
private static void exportToExcel(DataTable dt)
{
Excel.Application excel=new Excel.Application();
excel.Application.Workbooks.Add(true);
excel.Visible = true;

//get the columns
for (int i = 0; i < dt.Columns.Count;i++ )
{
//here is started with 1
//it looks like excele table start with 1 not 1
excel.Cells[1, i + 1] = dt.Columns[i].ColumnName.ToString();
}

//get the data in rows
for (int row = 0; row < dt.Rows.Count;row++ )
{
for (int col = 0; col < dt.Columns.Count; col++)
{
excel.Cells[row+2, col+1] = dt.Rows[row][dt.Columns[col]].ToString();
}
}
//FolderBrowserDialog path = new FolderBrowserDialog();//打开文件对话框
//path.ShowDialog();
//textBox1.Text = path.SelectedPath;//选择文件夹

//save excel
//excel.SaveWorkspace();

excel.Quit();
}

2. 在web应用中,可通过HttpContext.Response.write()来实现
[csharp] view plain
protected static void toExcel(DataTable da){
System.Web.HttpContext context = System.Web.HttpContext.Current;
context.Response.Clear();

foreach( DataColumn colum in da.Columns){
context.Response.Write(colum.ColumnName+"\t");
}

context.Response.Write(System.Environment.NewLine);

foreach (DataRow row in da.Rows) {
for (int i = 0; i < da.Rows.Count; i++)
{
context.Response.Write(row[i].ToString()+"\t");
}
context.Response.Write(System.Environment.NewLine);
}
context.Response.ContentType = "application/vnd.ms-excel";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=plan.xls");
context.Response.End();
}

D. 如何修改spring mvc poi 导出excel文件

首先要导入spring相关包,poi,和fileupload包,我是使用maven构建的。
一.导入excel
(1)使用spring上传文件
a.前台页面提交
<form name="excelImportForm" action="${pageContext.request.contextPath}/brand/importBrandSort" method="post" onsubmit="return checkImportPath();" enctype="multipart/form-data" id="excelImportForm">
<input type="hidden" name="ids" id="ids">
<div class="modal-body">
<div class="row gap">
<label class="col-sm-7 control-label"><input class="btn btn-default" id="excel_file" type="file" name="filename" accept="xls"/></label>
<div class="col-sm-3">

<input class="btn btn-primary" id="excel_button" type="submit" value="导入Excel"/>
</div>
</div>

</div>

<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" onClick="uncheckBoxes();">取消</button>
</div>
b.后台spring的controller进行相关操作,这里主要讲的是使用spring上传文件,和读取文件信息。
使用spring上传文件之前,需要配置bean。
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>@RequestMapping(value = "/importBrandSort", method = RequestMethod.POST)
public ModelAndView importBrandSort(@RequestParam("filename") MultipartFile file,

HttpServletRequest request,HttpServletResponse response) throws Exception {
String temp = request.getSession().getServletContext()

.getRealPath(File.separator)

+ "temp"; // 临时目录

File tempFile = new File(temp);

if (!tempFile.exists()) {

tempFile.mkdirs();
}

DiskFileUpload fu = new DiskFileUpload();

fu.setSizeMax(10 * 1024 * 1024); // 设置允许用户上传文件大小,单位:位
fu.setSizeThreshold(4096); // 设置最多只允许在内存中存储的数据,单位:位
fu.setRepositoryPath(temp); // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
// 开始读取上传信息
//
int index = 0;
/* List fileItems = null;

try {

fileItems = fu.parseRequest(request);
}
catch (Exception e) {

e.printStackTrace();
}

Iterator iter = fileItems.iterator(); // 依次处理每个上传的文件

FileItem fileItem = null;

while (iter.hasNext()) {

FileItem item = (FileItem) iter.next();// 忽略其他不是文件域的所有表单信息

if (!item.isFormField()) {

fileItem = item;
// index++;
}
}

if (fileItem == null)

return null;
*/
if (file == null)

return null;

logger.info(file.getOriginalFilename());

String name = file.getOriginalFilename();// 获取上传文件名,包括路径

//name = name.substring(name.lastIndexOf("\\") + 1);// 从全路径中提取文件名

long size = file.getSize();

if ((name == null || name.equals("")) && size == 0)

return null;
InputStream in = file.getInputStream();
List<BrandMobileInfoEntity> BrandMobileInfos = brandService
.importBrandPeriodSort(in);

// 改为人工刷新缓存KeyContextManager.clearPeriodCacheData(new

// PeriodDimensions());// 清理所有缓存

int count = BrandMobileInfos.size();

String strAlertMsg ="";

if(count!=0){

strAlertMsg= "成功导入" + count + "条!";

}else {

strAlertMsg = "导入失败!";
}

logger.info(strAlertMsg);

//request.setAttribute("brandPeriodSortList", BrandMobileInfos);
//request.setAttribute("strAlertMsg", strAlertMsg);

request.getSession().setAttribute("msg",strAlertMsg);

return get(request, response);

//return null;
}
代码中的注释部分是如果不使用spring的方式,如何拿到提交过来的文件名(需要是要apache的一些工具包),其实使用spring的也是一样,只是已经做好了封装,方便我们写代码。
代码中的后半部分是读取完上传文文件的信息和对数据库进行更新之后,输出到前台页面的信息。
上述代码中: InputStream in = file.getInputStream();
List<BrandMobileInfoEntity> BrandMobileInfos = brandService
.importBrandPeriodSort(in);读取excel的信息。
(2)使用poi读取excel
a.更新数据库
@Override
public List<BrandMobileInfoEntity> importBrandPeriodSort(InputStream in) throws Exception {

List<BrandMobileInfoEntity> brandMobileInfos = readBrandPeriodSorXls(in);
for (BrandMobileInfoEntity brandMobileInfo : brandMobileInfos) {
mapper.updateByConditions(brandMobileInfo);
}
return brandMobileInfos;
}
这部分是sevice层的代码,用于读取excel信息之后更新数据库数据,我这里是使用mybatis。定义一个类BrandMobileInfoEntity,用与保存excel表每一行的信息,而List< BrandMobileInfoEntity > 则保存了全部信息,利用这些信息对数据库进行更新。
b.读取excel信息
private List<BrandMobileInfoEntity> readBrandPeriodSorXls(InputStream is)
throws IOException, ParseException {
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
List<BrandMobileInfoEntity> brandMobileInfos = new ArrayList<BrandMobileInfoEntity>();
BrandMobileInfoEntity brandMobileInfo;
// 循环工作表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++) {
brandMobileInfo = new BrandMobileInfoEntity();

HSSFRow hssfRow = hssfSheet.getRow(rowNum);

for (int i = 0; i < hssfRow.getLastCellNum(); i++) {

HSSFCell brandIdHSSFCell = hssfRow.getCell(i);

if (i == 0) {

brandMobileInfo.setBrandId(Integer

.parseInt(getCellValue(brandIdHSSFCell)));

} else if (i == 1) {

continue;

} else if (i == 2) {

brandMobileInfo.setMobileShowFrom(Integer.parseInt(getCellValue(brandIdHSSFCell)));

} else if (i == 3) {

brandMobileInfo.setMobileShowTo(Integer.parseInt(getCellValue(brandIdHSSFCell)));

} else if (i == 4) {

brandMobileInfo.setSellMarkValue(getCellValue(brandIdHSSFCell));

} else if (i == 5) {

brandMobileInfo.setWarehouse(getCellValue(brandIdHSSFCell));

} else if (i == 6) {

brandMobileInfo.setSortA1(Integer.parseInt(getCellValue(brandIdHSSFCell)));
} else if (i == 7) {

brandMobileInfo.setSortA2(Integer.parseInt(getCellValue(brandIdHSSFCell)));
} else if (i == 8) {

brandMobileInfo.setSortB(Integer.parseInt(getCellValue(brandIdHSSFCell)));
} else if (i == 9) {

brandMobileInfo.setSortC10(Integer.parseInt(getCellValue(brandIdHSSFCell)));
}
else if (i == 10) {

brandMobileInfo.setSortC(Integer.parseInt(getCellValue(brandIdHSSFCell)));

} else if (i == 11) {

brandMobileInfo.setHitA(getCellValue(brandIdHSSFCell));

} else if (i == 12) {

brandMobileInfo.setHitB(getCellValue(brandIdHSSFCell));

} else if (i == 13) {

brandMobileInfo.setHitC(getCellValue(brandIdHSSFCell));

} else if (i == 14) {

brandMobileInfo.setCustomSellType(getCellValue(brandIdHSSFCell));

}else if (i == 15)
{
continue;

}else if (i == 16) {

brandMobileInfo.setChannelId(Integer.parseInt(getCellValue(brandIdHSSFCell)));

}

}
brandMobileInfos.add(brandMobileInfo);

}
}
return brandMobileInfos;
}
这种代码有点搓,还没有优化,可以大概看到是怎么读取信息的。
(3)使用mybatis更新数据。

E. poi导出excel用哪个jar包最好

java导出Excel需要用到poi的jar包,
// 第一步,创建一个webbook,对应一个Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet("学生表一");
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
HSSFRow row = sheet.createRow((int) 0);
// 第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

HSSFCell cell = row.createCell((short) 0);
cell.setCellValue("学号");
cell.setCellStyle(style);
cell = row.createCell((short) 1);
cell.setCellValue("姓名");
cell.setCellStyle(style);
cell = row.createCell((short) 2);
cell.setCellValue("年龄");
cell.setCellStyle(style);
cell = row.createCell((short) 3);
cell.setCellValue("生日");
cell.setCellStyle(style);

// 第五步,写入实体数据 实际应用中这些数据从数据库得到,
List list = CreateSimpleExcelToDisk.getStudent();

for (int i = 0; i < list.size(); i++)
{
row = sheet.createRow((int) i + 1);
Student stu = (Student) list.get(i);
// 第四步,创建单元格,并设置值
row.createCell((short) 0).setCellValue((double) stu.getId());
row.createCell((short) 1).setCellValue(stu.getName());
row.createCell((short) 2).setCellValue((double) stu.getAge());
cell = row.createCell((short) 3);
cell.setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(stu
.getBirth()));
}
// 第六步,将文件存到指定位置
try
{
FileOutputStream fout = new FileOutputStream("E:/students.xls");
wb.write(fout);
fout.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}

F. 如何使用POI对Excel表进行导入和导出

导入POI的jar包
新建一个项目,在根目录在新建一个lib文件夹,将jar包复制粘贴到lib文件夹后,右键将其添加到项目的build path中,最后的结果如图所示:

2
编写java类,新建一个实体类,比如我们要导出数据库的有关电脑的信息,那么就建一个Computer实体类,代码如下:
package com.qiang.poi;
public class Computer {
private int id;
private String name;
private String description;
private double price;
private double credit;
public int getId() {
return id;
}
public Computer(int id, String name, String description, double price,
double credit) {
super();
this.id = id;
this.name = name;
this.description = description;
this.price = price;
this.credit = credit;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public double getCredit() {
return credit;
}
public void setCredit(double credit) {
this.credit = credit;
}
}
3
新建一个写入excel的方法,如write2excel,参数可以后面边写边决定(站在一个不熟悉POI的角度)
public static void write2Excel(){}
4
创建操作Excel的HSSFWorkbook对象
HSSFWorkbook excel= new HSSFWorkbook();
创建HSSFSheet对象
Excel中的一个sheet(工作表)对应着java中的一个HSSFSheet对象,利用HSSFWorkbook对象可以创建一个HSSFSheet对象
如:创建一个sheet名为computer的excel
HSSFSheet sheet = excel.createSheet("computer");
创建第一行标题信息的HSSFRow对象
我们都知道excel是表格,即由一行一行组成的,那么这一行在java类中就是一个HSSFRow对象,我们通过HSSFSheet对象就可以创建HSSFRow对象
如:创建表格中的第一行(我们常用来做标题的行) HSSFRow firstRow = sheet.createRow(0); 注意下标从0开始
创建标题行中的HSSFCell数组
当然,excel中每一行是由若干个单元格,我们常称为cell,它对应着java中的HSSFCell对象
如:创建5个单元格 HSSFCell cells[] = new HSSFCell[5];
//假设我们一行有五列数据
创建标题数据,并通过HSSFCell对象的setCellValue()方法对每个单元格进行赋值
既然单元格都准备好了,那最后是不是该填充数据了呀。对的,没错。填充数据之前,得把数据准备好吧,
数据:String[] titles = new String[]{"id","name","description","price","credit"};
插入一句话: 在这个时代,能让机器做的,尽量不让人来做,记住这句话。
好的,继续。现在就通过for循环来填充第一行标题的数据
for (int i = 0; i < 5; i++) {
cells[0] = firstRow.createCell(i);
cells[0].setCellValue(titles[i]);
}
数据分析
第一行标题栏创建完毕后,就准备填充我们要写入的数据吧,在java中,面向对象给我们带来的好处在这里正好体现了,没错
把要填写的数据封装在对象中,即一行就是一个对象,n行就是一个对象列表嘛,好的,走起。
创建对象Computer,私有属性id,name,description,price,credit,以及各属性的setter和getter方法,如步骤二所示。
假设我们要写入excel中的数据从数据库查询出来的,最后就生成了一个List<Computer>对象computers
数据写入
具体数据有了,又该让机器帮我们干活了,向excel中写入数据。
for (int i = 0; i < computers.size(); i++) {
HSSFRow row = sheet.createRow(i + 1);
Computer computer = computers.get(i);
HSSFCell cell = row.createCell(0);
cell.setCellValue(computer.getId());
cell = row.createCell(1);
cell.setCellValue(computer.getName());
cell = row.createCell(2);
cell.setCellValue(computer.getDescription());
cell = row.createCell(3);
cell.setCellValue(computer.getPrice());
cell = row.createCell(4);
cell.setCellValue(computer.getCredit());
}
将数据真正的写入excel文件中
做到这里,数据都写好了,最后就是把HSSFWorkbook对象excel写入文件中了。
OutputStream out = null;
try {
out = new FileOutputStream(file);
excel.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("数据已经写入excel"); //温馨提示
看看我的main方法吧
public static void main(String[] args) throws IOException {
File file = new File("test1.xls");
if(!file.exists()){
file.createNewFile();
}
List<Computer> computers = new ArrayList<Computer>();
computers.add(new Computer(1,"宏碁","笔记本电脑",3333,9.0));
computers.add(new Computer(2,"苹果","笔记本电脑,一体机",8888,9.6));
computers.add(new Computer(3,"联想","笔记本电脑,台式机",4444,9.3));
computers.add(new Computer(4, "华硕", "笔记本电脑,平板电脑",3555,8.6));
computers.add(new Computer(5, "注解", "以上价格均为捏造,如有雷同,纯属巧合", 1.0, 9.9));
write2excel(computers, file);
}
工程目录及执行main方法后的test1.xls数据展示

源码分享,computer就不贴了
package com.qiang.poi;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
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;
public class ReadExcel {
public static void main(String[] args) throws IOException {
File file = new File("test1.xls");
if(!file.exists()){
file.createNewFile();
}
List<Computer> computers = new ArrayList<Computer>();
computers.add(new Computer(1,"宏碁","笔记本电脑",3333,9.0));
computers.add(new Computer(2,"苹果","笔记本电脑,一体机",8888,9.6));
computers.add(new Computer(3,"联想","笔记本电脑,台式机",4444,9.3));
computers.add(new Computer(4, "华硕", "笔记本电脑,平板电脑",3555,8.6));
computers.add(new Computer(5, "注解", "以上价格均为捏造,如有雷同,纯属巧合", 1.0, 9.9));
write2excel(computers, file);
}

public static void write2excel(List<Computer> computers,File file) {
HSSFWorkbook excel = new HSSFWorkbook();
HSSFSheet sheet = excel.createSheet("computer");
HSSFRow firstRow = sheet.createRow(0);
HSSFCell cells[] = new HSSFCell[5];
String[] titles = new String[] { "id", "name", "description", "price",
"credit" };
for (int i = 0; i < 5; i++) {
cells[0] = firstRow.createCell(i);
cells[0].setCellValue(titles[i]);
}
for (int i = 0; i < computers.size(); i++) {
HSSFRow row = sheet.createRow(i + 1);
Computer computer = computers.get(i);
HSSFCell cell = row.createCell(0);
cell.setCellValue(computer.getId());
cell = row.createCell(1);
cell.setCellValue(computer.getName());
cell = row.createCell(2);
cell.setCellValue(computer.getDescription());
cell = row.createCell(3);
cell.setCellValue(computer.getPrice());
cell = row.createCell(4);
cell.setCellValue(computer.getCredit());
}
OutputStream out = null;
try {
out = new FileOutputStream(file);
excel.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

G. java 使用POI导出Excel文件,打开导出文件时报错

在保护状态下execl的格式有可能正在被使用,你这边修改,准确说是线程冲突,一般excel值会作为导出文件的模板,是不会编辑的。你可以在读的时候判断execl是否正在被使用。
下面的代码问题,你可以参考
package com.hwt.glmf.common;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
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;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;

/**
* 导出Excel公共方法
* @version 1.0
*
* @author wangcp
*
*/
public class ExportExcel extends BaseAction {

//显示的导出表的标题
private String title;
//导出表的列名
private String[] rowName ;

private List<Object[]> dataList = new ArrayList<Object[]>();

HttpServletResponse response;

//构造方法,传入要导出的数据
public ExportExcel(String title,String[] rowName,List<Object[]> dataList){
this.dataList = dataList;
this.rowName = rowName;
this.title = title;
}

/*
* 导出数据
* */
public void export() throws Exception{
try{
HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作簿对象
HSSFSheet sheet = workbook.createSheet(title); // 创建工作表

// 产生表格标题行
HSSFRow rowm = sheet.createRow(0);
HSSFCell cellTiltle = rowm.createCell(0);

//sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面 - 可扩展】
HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);//获取列头样式对象
HSSFCellStyle style = this.getStyle(workbook); //单元格样式对象

sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length-1)));
cellTiltle.setCellStyle(columnTopStyle);
cellTiltle.setCellValue(title);

// 定义所需列数
int columnNum = rowName.length;
HSSFRow rowRowName = sheet.createRow(2); // 在索引2的位置创建行(最顶端的行开始的第二行)

// 将列头设置到sheet的单元格中
for(int n=0;n<columnNum;n++){
HSSFCell cellRowName = rowRowName.createCell(n); //创建列头对应个数的单元格
cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); //设置列头单元格的数据类型
HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
cellRowName.setCellValue(text); //设置列头单元格的值
cellRowName.setCellStyle(columnTopStyle); //设置列头单元格样式
}

//将查询出的数据设置到sheet对应的单元格中
for(int i=0;i<dataList.size();i++){

Object[] obj = dataList.get(i);//遍历每个对象
HSSFRow row = sheet.createRow(i+3);//创建所需的行数

for(int j=0; j<obj.length; j++){
HSSFCell cell = null; //设置单元格的数据类型
if(j == 0){
cell = row.createCell(j,HSSFCell.CELL_TYPE_NUMERIC);
cell.setCellValue(i+1);
}else{
cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING);
if(!"".equals(obj[j]) && obj[j] != null){
cell.setCellValue(obj[j].toString()); //设置单元格的值
}
}
cell.setCellStyle(style); //设置单元格样式
}
}
//让列宽随着导出的列长自动适应
for (int colNum = 0; colNum < columnNum; colNum++) {
int columnWidth = sheet.getColumnWidth(colNum) / 256;
for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
HSSFRow currentRow;
//当前行未被使用过
if (sheet.getRow(rowNum) == null) {
currentRow = sheet.createRow(rowNum);
} else {
currentRow = sheet.getRow(rowNum);
}
if (currentRow.getCell(colNum) != null) {
HSSFCell currentCell = currentRow.getCell(colNum);
if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
int length = currentCell.getStringCellValue().getBytes().length;
if (columnWidth < length) {
columnWidth = length;
}
}
}
}
if(colNum == 0){
sheet.setColumnWidth(colNum, (columnWidth-2) * 256);
}else{
sheet.setColumnWidth(colNum, (columnWidth+4) * 256);
}
}

if(workbook !=null){
try
{
String fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls";
String headStr = "attachment; filename=\"" + fileName + "\"";
response = getResponse();
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", headStr);
OutputStream out = response.getOutputStream();
workbook.write(out);
}
catch (IOException e)
{
e.printStackTrace();
}
}

}catch(Exception e){
e.printStackTrace();
}

}

/*
* 列头单元格样式
*/
public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {

// 设置字体
HSSFFont font = workbook.createFont();
//设置字体大小
font.setFontHeightInPoints((short)11);
//字体加粗
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//设置字体名字
font.setFontName("Courier New");
//设置样式;
HSSFCellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//设置左边框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//设置右边框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//设置顶边框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

return style;

}

/*
* 列数据信息单元格样式
*/
public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
// 设置字体
HSSFFont font = workbook.createFont();
//设置字体大小
//font.setFontHeightInPoints((short)10);
//字体加粗
//font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//设置字体名字
font.setFontName("Courier New");
//设置样式;
HSSFCellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//设置左边框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//设置右边框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//设置顶边框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

return style;

}
}

H. 如何用JAVA导出Excel(使用POI)

导出Excle有3种方法,
第一是使用POI组件操作Excle
第二是使用JXL组件操作Excle
第三是最简单的,静态生成Excle
推荐第3中。不用话时间去学习
下面是静态生成Excle具体实现:
在你 index.jsp中写脚本函数:

<script type="text/javascript">
function saveToExcel(tableId,fileName){
var table = document.getElementById(tableId);
ToExcel.tableContent.value = table.outerHTML;
if(fileName==null){fileName = "export";}
ToExcel.fileName.value = fileName;
ToExcel.submit();
}
</script>
写一个form
<form name="ToExcel" id="ToExcel" method="post" action="createExcel.jsp" target="_blank">
<input type="hidden" name="tableContent" value="" readonly/>
<input type="hidden" name="fileName" value="" readonly/>
</form>
写一个链接
<a href="javascript:saveToExcel('ec_table','equipment.xls')">导出数据</a>
再创建一个jsp页面createExcel.jsp
以下是页面内容
<%@ page language="java" contentType="text/html;charset=UTF-8"%>
<%!
private String encode(String str){
String nStr = "";
try{
nStr = new String(str.getBytes("ISO-8859-1"),"UTF-8");
}catch(Exception e){
}
return nStr;
}
%>

<%
request.setCharacterEncoding("UTF-8");
response.setContentType("application/vnd.ms-excel; charset=UTF-8");
String path=request.getContextPath();
String tableContent = request.getParameter("tableContent");
String fileName = encode(request.getParameter("fileName"));
response.setHeader("Content-disposition", "inline; filename=" +fileName);
%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="<%=path%>/css/pingtai.css" rel="stylesheet" type="text/css" />
</head>
<body>
<%out.print(tableContent);%>
</body>
</html>

以上的代码可以直接复制使用,如果有什么看不明白的,可以继续问我

I. java从数据库中导出excel poi

这个我做奖金,考勤系统的时候经常用到,是一个方法,希望能帮到你。
用的apache poi:
/**
* 将奖金列表转换为奖金报表
* @param bonus
* @return byte[]
*/
private byte[] mainProcessBonusListToReport(List<Bonus> bonuses){
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
HSSFSheet hssfSheet =hssfWorkbook.createSheet("总奖金报表单");
/*第一行单元格合并*/

hssfSheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 12));
/*第一行*/

HSSFRow hssfRow = hssfSheet.createRow(0);
HSSFCell hssfCell=hssfRow.createCell(0);
hssfCell.setCellValue("派单业务考核记录");
/*第二行*/

hssfRow = hssfSheet.createRow(1);
/*列名*/

String[] titles = {"序号","工号","话务员姓名","规范奖考核","业务奖金","话务奖金","服务质量奖金","星级系数","组长津贴","总奖金","增资奖金","英语翻译","实发总奖金"};
/*for循环生成列名*/

for (int i = 0; i < titles.length; i++) {
hssfCell = hssfRow.createCell(i);
hssfCell.setCellValue(titles[i]);
}
/*填充数据*/

int rowIndex=2;
for (Bonus bonus : bonuses) {
hssfRow = hssfSheet.createRow(rowIndex);
hssfCell = hssfRow.createCell(0);
hssfCell.setCellValue(rowIndex-1);
hssfCell = hssfRow.createCell(1);
hssfCell.setCellValue(bonus.getWorkNumber());
hssfCell = hssfRow.createCell(2);
hssfCell.setCellValue(bonus.getName());
hssfCell = hssfRow.createCell(3);
hssfCell.setCellValue(bonus.getStandardPerformance());
hssfCell = hssfRow.createCell(4);
hssfCell.setCellValue(bonus.getBusinessBonus());
hssfCell = hssfRow.createCell(5);
hssfCell.setCellValue(bonus.getCallBonus());
hssfCell = hssfRow.createCell(6);
hssfCell.setCellValue(bonus.getServiceQualityBonus());
hssfCell = hssfRow.createCell(7);
hssfCell.setCellValue(bonus.getStarCoefficient());
hssfCell = hssfRow.createCell(8);
hssfCell.setCellValue(bonus.getGroupLeaderAllowance());
hssfCell = hssfRow.createCell(9);
hssfCell.setCellValue(bonus.getTotalBonus());
hssfCell = hssfRow.createCell(10);
hssfCell.setCellValue(bonus.getAdditionalBonus());
hssfCell = hssfRow.createCell(11);
hssfCell.setCellValue(bonus.getEnglishTranslateBonus());
hssfCell = hssfRow.createCell(12);
hssfCell.setCellValue(bonus.getActualTotalBonus());
rowIndex++;
}
byte[] bytes = TypeUtils.HSSFWorkbookToByteArray(hssfWorkbook);
return bytes;
}