當前位置:首頁 » 數據倉庫 » poi從資料庫導出excel文件
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

poi從資料庫導出excel文件

發布時間: 2022-09-25 13:18:54

1. 如何將資料庫文件導出為EXCEL文件

1.首先使用sqlyogEnt工具,連接到mysql資料庫。
2.連接成功後在左側的目錄位置,找到需要的表,右鍵打開表。
3.也可以直接在sql執行器中輸入:
select
*
from
datetable
name
打開這個表。
4.在sql執行器的下方,結果下方,最左側的位置,如下圖,有一個小圖標,滑鼠移動上面會浮出文字「導出為....」點擊這個圖標。
5.點擊後會彈出一個名為「導出為」的彈出窗口,選擇需要導出的文件格式:如csv、html、xnl等,在右側選擇導出的欄位。
在界面的最下方有一個輸入框,框中是程序默認的一個導出的路徑,也可以點擊路徑旁的按鈕,進行自定義導出文件路徑。
6.最後點擊【導出】按鈕,點擊後會有一個小的提示窗,提示信息為「date
exporet
successfully」點擊【確定】按鈕,完成導出操作。
7.最後就是在導出目錄中找到導出的文件,查看導出是否成功。
這里需要注意一下,csv格式的文件,如果用excel打開會出現亂碼,因為編碼不同,如果使用txt打開則不會有這樣的問題。

2. java用poi導出excel文件,打開導出的文件時報錯,怎麼辦

兩個原因:

1.你的excel模版本身有問題,可以嘗試新建一個模版。

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

解決辦法:

另存是由excel重寫了完整的文件,可以解決問題。

關閉文件例子:

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

wb.write(os);

os.close();

3. 利用POI技術從資料庫里提取數據,生成一個Excel文檔或者Word文檔

http://java.ccidnet.com/art/3737/20030321/479599_1.html

代碼:

HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet = wb.createSheet();ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();BufferedImage bufferImg = ImageIO.read(new File("D:\\fruit.PNG"));ImageIO.write(bufferImg,"PNG",byteArrayOut);HSSFClientAnchor anchor = new HSSFClientAnchor(5,0,500,122,(short) 0, 5,(short)10,15); HSSFPatriarch patri = sheet.createDrawingPatriarch();patri.createPicture(anchor , wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG)); ByteArrayOutputStream outStream = new ByteArrayOutputStream();wb.write(outStream);

上面代碼只是大概,但需要用到的類都已經列出。接下來需要做的就是把 outStream輸出到excel文件中去了。

具體的類的document可以去下面網站上查看:
http://jakarta.apache.org/poi/apidocs/org/apache/poi/hssf/usermodel/HSSFWorkbook.html

補充......
http://deepfuture.javaeye.com/blog/615081

java poi-讀寫word、excel
package zl.file;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;

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;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

// code run against the jakarta-poi-1.5.0-FINAL-20020506.jar.
public class MyExcel {

static public void main(String[] args) throws Exception {
//------------在xls中寫入數據
FileOutputStream fos = new FileOutputStream("e:\\text.xls");
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet();
wb.setSheetName(0, "first sheet");
HSSFRow row = s.createRow(0);
HSSFCell cell = row.createCell((short)0,0);
HSSFRichTextString hts=new HSSFRichTextString("nihao");
cell.setCellValue(hts);
wb.write(fos);
fos.flush();
fos.close();
//------------從xls讀出數據
wb = new HSSFWorkbook(new FileInputStream("e:\\text.xls"));
s = wb.getSheetAt(0);
HSSFRow r = s.getRow(0);
cell=r.getCell((short)0);
if(cell.getCellType() == HSSFCell.CELL_TYPE_STRING){
System.out.println(cell.getRichStringCellValue());
}
//------------從doc讀出數據
FileInputStream in = new FileInputStream("e:\\text.doc");
WordExtractor extractor = new WordExtractor(in);
String text =extractor.getText();
// 對DOC文件進行提取
System.out.println(text);
in.close();
//------------------在doc中寫入

byte[] a=new String("看見了!").getBytes();
ByteArrayInputStream bs = new ByteArrayInputStream(a);
POIFSFileSystem fs = new POIFSFileSystem();
///////////////////////////////////
DirectoryEntry directory = fs.getRoot();
DocumentEntry de = directory.createDocument("WordDocument", bs);
//以上兩句代碼不能省略,否則輸出的是亂碼
fos = new FileOutputStream("e:\\text.doc");
fs.writeFilesystem(fos);
bs.close();
fos.flush();
fos.close();
}
}

4. POI導出Excel,復制行

在日常開發中,導出Excel應該是很常見了,最近有一個需求要動態填充模板內容,試了很多辦法,最後採用復制行來搞定。

上圖顯示的可多填,都有可能出現多個保證人或者房產抵押信息,這時候就要根據內容動態修改模板,然後再賦值導出了。

該示例工程已完善並提交到gitee倉庫,地址如下:

row

5. 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");

6. 怎麼利用POI 從JSP表格中導出excel文件

兩種方式:
1、直接提取頁面數據,組織成EXCEL
2、提交到原請求,用參數來判斷是否生成EXCEL,而數據則用原來請求數據

7. poi導出Excel問題

你的方法應該是沒有問題,404錯誤只是你的跳轉沒響應,估計跳轉頁面路徑錯了。沒有你的配置文件不好說

8. 如何修改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更新數據。

9. 關於POI的高級問題,關於把數據導出到excel表中

select count(*),籍貫 from tablename group by 籍貫
用這個查詢出結果,怎麼用poi不用寫了吧,隨便搜索一下就有了。