當前位置:首頁 » 數據倉庫 » 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;
}