導航:首頁 > 文件類型 > java導出excel下載文件

java導出excel下載文件

發布時間:2023-05-27 18:41:22

java代碼怎麼導出excel文件

excel工具
package com.ohd.ie.proct.action;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import org.apache.commons.io.output.ByteArrayOutputStream;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.VerticalAlignment;
import jxl.write.*;
import jxl.write.Number;
import jxl.write.biff.RowsExceededException;
public class Excel {
private OutputStream os;
private WritableWorkbook wwb = null;
private WritableSheet ws = null;
private WritableCellFormat titleCellFormat = null;
private WritableCellFormat noBorderCellFormat = null;
private WritableCellFormat hasBorderCellFormat = null;
private WritableCellFormat hasBorderCellNumberFormat = null;
private WritableCellFormat hasBorderCellNumberFormat2 = null;
private WritableImage writableImage=null;
private int r;
public Excel(OutputStream os){
this.os = os;
r = -1;
try {
wwb = Workbook.createWorkbook(os);
//創建工作表
ws = wwb.createSheet("sheet1",0);
//設置表頭字體,大小,加粗
titleCellFormat = new WritableCellFormat();
titleCellFormat.setAlignment(Alignment.CENTRE);
titleCellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
//自動換行
titleCellFormat.setWrap(true);
titleCellFormat.setFont(new WritableFont(WritableFont.createFont("宋體"),12,WritableFont.BOLD));
titleCellFormat.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
//設置表格字體,大小----無邊框
noBorderCellFormat = new WritableCellFormat();
noBorderCellFormat.setAlignment(Alignment.CENTRE);
noBorderCellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
noBorderCellFormat.setFont(new WritableFont(WritableFont.createFont("宋體"),12));
//設置表格字體,大小----有邊框
hasBorderCellFormat = new WritableCellFormat();
hasBorderCellFormat.setAlignment(Alignment.CENTRE);
hasBorderCellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
hasBorderCellFormat.setFont(new WritableFont(WritableFont.createFont("宋體"),12));
hasBorderCellFormat.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
//設置表格字體,大小----有邊框(小數)
NumberFormat nf = new NumberFormat("#0.00");
hasBorderCellNumberFormat = new WritableCellFormat(nf);
hasBorderCellNumberFormat.setAlignment(Alignment.CENTRE);
hasBorderCellNumberFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
hasBorderCellNumberFormat.setFont(new WritableFont(WritableFont.createFont("宋體"),12));
hasBorderCellNumberFormat.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
//設置表格字體,大小----有邊框(整數)
NumberFormat nf2 = new NumberFormat("#0");
hasBorderCellNumberFormat2 = new WritableCellFormat(nf2);
hasBorderCellNumberFormat2.setAlignment(Alignment.CENTRE);
hasBorderCellNumberFormat2.setVerticalAlignment(VerticalAlignment.CENTRE);
hasBorderCellNumberFormat2.setFont(new WritableFont(WritableFont.createFont("宋體"),12));
hasBorderCellNumberFormat2.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*
* @param content 內容
* @param c 列
* @param style 樣式
* @param isNewLine 是否換行
* @param mergeType 合並類型
* @param mergeCount 合並個數
* @param width 單元格寬
*/
public void setExcelCell(String content,int c,int style,boolean isNewLine,int mergeType,int mergeCount,int width){
try {
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////報表內容////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
if(isNewLine){
r++;
}
WritableCell l = null;
if(style == 1){
l = new Label(c,r,content,titleCellFormat);
}
else if(style == 2){
l = new Label(c,r,content,noBorderCellFormat);
}
else if(style == 3){
l = new Label(c,r,content,hasBorderCellFormat);
}
else if(style == 4){
l = new Number(c,r,Double.parseDouble(content),hasBorderCellNumberFormat);
}
else if(style == 5){
l = new Number(c,r,Integer.parseInt(content),hasBorderCellNumberFormat2);
}
ws.addCell(l);
if(width != 0){
ws.setColumnView(c,width);
}
//veryhuo,com
if(mergeType == 1){
//x 軸方向
ws.mergeCells(c, r, c+mergeCount-1 , r);
}
else if(mergeType == 2){
//y 軸方向
ws.mergeCells(c, r, c, r+mergeCount-1);
}
if(isNewLine){
ws.setRowView(r, 350);
if(style == 1 && r != 0){
ws.setRowView(r, 900);
}
else{
ws.setRowView(r, 350);
}
}
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
} catch (Exception e) {
System.out.println(e.toString());
}
}
public void setExcelCellEx(String content,int c,int style,boolean isNewLine,int mergeType,int mergeCount,int width,int row){
try {
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////報表內容////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
if(isNewLine){
r++;
}
WritableCell l = null;
if(style == 1){
l = new Label(c,r,content,titleCellFormat);
}
else if(style == 2){
l = new Label(c,r,content,noBorderCellFormat);
}
else if(style == 3){
if(content.indexOf(".jpg")!=-1 ||content.indexOf(".JPG")!=-1){
File outputFile=null;
File imgFile =new File(content);
if(imgFile.exists()&&imgFile.length()>0){
BufferedImage input=null;
try {
input = ImageIO.read(imgFile);
} catch (Exception e) {
e.printStackTrace();
}
if(input!=null){
String path=imgFile.getAbsolutePath();
outputFile = new File(path.substring(0,path.lastIndexOf('.')+1)+"png");
ImageIO.write(input, "PNG", outputFile);
if(outputFile.exists()&&outputFile.length()>0){
ws.setRowView(row,2000);
//ws.setColumnView(8, 10);
writableImage = new WritableImage(c+0.1, row+0.1, 0.8, 0.8, outputFile);
ws.addImage(writableImage);
l = new Label(c,r,"",hasBorderCellFormat);
}
}
}
}else{
l = new Label(c,r,content,hasBorderCellFormat);
}
}
else if(style == 4){
l = new Number(c,r,Double.parseDouble(content),hasBorderCellNumberFormat);
}
else if(style == 5){
l = new Number(c,r,Integer.parseInt(content),hasBorderCellNumberFormat2);
}
ws.addCell(l);
if(width != 0){
ws.setColumnView(c,width);
}
if(mergeType == 1){
//x 軸方向
ws.mergeCells(c, r, c+mergeCount-1 , r);
}
else if(mergeType == 2){
//y 軸方向
ws.mergeCells(c, r, c, r+mergeCount-1);
}
if(isNewLine){
ws.setRowView(r, 350);
if(style == 1 && r != 0){
ws.setRowView(r, 900);
}
else{
ws.setRowView(r, 350);
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
}
public void setRowHeight(int val){
try {
ws.setRowView(r, val);
} catch (RowsExceededException e) {
e.printStackTrace();
}
}
public void getExcelResult(){
try {
wwb.write();
} catch (Exception e) {
System.out.println(e.toString());
}
finally{
if(wwb != null){
try {
wwb.close();
if(os != null){
os.close();
}
} catch (WriteException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
需要的jar包:jxl.jar

Ⅱ 如何用JAVA導出Excel(使用POI)

response.setContentType("bin");
response.setHeader("Content-disposition","attachment;filename=test.xls");
你在servlet裡面設置響應頭為這樣,然後就能夠實現下載了,然後使用輸出流進行輸出下載
.....還有問題的話就問..
你要是想全部代碼都寫的話..加我扣扣 1195391953..

Ⅲ java如何將導出的excel下載到客戶端

packagecom.mr;

importjava.io.IOException;
importjava.io.PrintWriter;

importjavax.servlet.ServletException;
importjavax.servlet.ServletOutputStream;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
/**
*利用Servlet導出Excel
*@N
*
*/
{

publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
doPost(request,response);
}

publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
request.setCharacterEncoding("UTF-8");//設置request的編碼方式,防止中文亂碼
StringfileName="導出數據";//設置導出的文件名稱
StringBuffersb=newStringBuffer(request.getParameter("tableInfo"));//將表格信息放入內存
StringcontentType="application/vnd.ms-excel";//定義導出文件的格式的字元串
StringrecommendedName=newString(fileName.getBytes(),"iso_8859_1");//設置文件名稱的編碼格式
response.setContentType(contentType);//設置導出文件格式
response.setHeader("Content-Disposition","attachment;filename="+recommendedName+""");//
response.resetBuffer();
//利用輸出輸入流導出文件
ServletOutputStreamsos=response.getOutputStream();
sos.write(sb.toString().getBytes());
sos.flush();
sos.close();
}
}
<%@pagelanguage="java"contentType="text/html;charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=UTF-8">
<title>導出Excel</title>
<scripttype="text/javascript">
functiontest(){
document.getElementById("tableInfo").value=document.getElementById("table").innerHTML;
}
</script>
<style>
body{font-family:宋體;font-size:11pt}
</style>
</head>
<body>
<formaction="<%=request.getContextPath()%>/servlet/ExportExcelServlet"method="post">
<spanid="table">
<tablebgcolor="#EEECF2"bordercolor="#A3B2CC"border="1"cellspacing="0">
<tr><th>學號</th><th>姓名</th><th>科目</th><th>分數</th></tr>
<tr><td>10001</td><td>趙二</td><td>高數</td><td>82</td></tr>
<tr><td>10002</td><td>張三</td><td>高數</td><td>94</td></tr>
<tr><td>10001</td><td>趙二</td><td>線數</td><td>77</td></tr>
<tr><td>10002</td><td>張三</td><td>線數</td><td>61</td></tr>
</table>
</span><br/>
<inputtype="submit"name="Excel"value="導出表格"onclick="test()"/>
<inputtype="hidden"id="tableInfo"name="tableInfo"value=""/>
</form>
</body>
</html>

以上代碼來自網路:http://jtlyuan.iteye.com/blog/1322097

Ⅳ 如何導出生成excel文件 java

在編程中經常需要使用到表格(報表)的處理主要以Excel表格為主。下面給出用java寫入數據到excel表格方法:
1.添加jar文件

java導入導出Excel文件要引入jxl.jar包,最關鍵的是這套API是純Java的,並不依賴Windows系統,即使運行在Linux下,它同樣能夠正確的處理Excel文件。下載地址:http://www.andykhan.com/jexcelapi/

2.jxl對Excel表格的認識

可以參見http://www.cnblogs.com/xudong-bupt/archive/2013/03/19/2969997.html

3.java代碼根據程序中的數據生成上述圖片所示的t.xls文件

?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

import java.io.File;
import jxl.*;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class Writer_excel{
public static void main(String[] args) {
//標題行
String title[]={"角色","編號","功能名稱","功能描述"};
//內容
String context[][]={{"UC11","設置課程","創建課程"},
{"UC12","設置學生名單","給出與課程關聯的學生名單"},
{"UC21","查看學生名單",""},
{"UC22","查看小組信息","顯示助教所負責的小組列表信息"}
};
//操作執行
try {
//t.xls為要新建的文件名
WritableWorkbook book= Workbook.createWorkbook(new File("t.xls"));
//生成名為「第一頁」的工作表,參數0表示這是第一頁
WritableSheet sheet=book.createSheet("第一頁",0);

//寫入內容
for(int i=0;i<4;i++) //title
sheet.addCell(new Label(i,0,title[i]));
for(int i=0;i<4;i++) //context
{
for(int j=0;j<3;j++)
{
sheet.addCell(new Label(j+1,i+1,context[i][j]));
}
}
sheet.addCell(new Label(0,1,"教師"));
sheet.addCell(new Label(0,3,"助教"));

/*合並單元格.合並既可以是橫向的,也可以是縱向的
*WritableSheet.mergeCells(int m,int n,int p,int q); 表示由(m,n)到(p,q)的單元格組成的矩形區域合並
* */
sheet.mergeCells(0,1,0,2);
sheet.mergeCells(0,3,0,4);

//寫入數據
book.write();
//關閉文件
book.close();
}
catch(Exception e) { }
}

Ⅳ java如何另存導出Excel

1./**

* 出險信息導出到excel(fc)

* @param mapping

* @param form

* @param request

* @param response

* @throws IOException

*/

public void exportActoExcel(ActionMapping mapping, ActionForm form ,

HttpServletRequest request,HttpServletResponse response) throws IOException {

ActionErrors errors = new ActionErrors();

AcExcelBusi acBusi = new AcExcelBusi();

AccidentRecordForm arForm= (AccidentRecordForm) form;

AccidentRecordBusi arBusi = new AccidentRecordBusi();

// ////查詢條件

FwUsers sessUser = (FwUsers)request.getSession().getAttribute(ConstValues.SESS_USER_MANAGE);

Map<String,Object> cisMap = arBusi.getTodoPageList(arForm,sessUser,errors);

List AcList = null;// 當頁的記錄

if (null != cisMap) {

AcList = (List) cisMap.get("list");

}


//導出excel的路徑、文件名

String uuid = UUID.create("exp");

String path = request.getSession().getServletContext().getRealPath("/") + ConstValues.EXP_PATH_EXCEL + uuid + ".xls";

acBusi.exprotAcExcel(AcList, path,request);


response.sendRedirect("stdownload.jsp?path=" + path );


}

Ⅵ 怎麼用java實現導出excel

/**
*@authorliuwu
* Excel的導入與導出
*/
@SuppressWarnings({"unchecked"})
publicclassExcelOperate{
/**
*@authorliuwu
*這是一個通用的方法,利用了JAVA的反射機制,
*可以將放置在JAVA集合中並且符合一定條件的數據以EXCEL的形式輸出到指定IO設備上
*@paramtitle表格標題名
*@paramheaders表格屬性列名數組
*@paramdataset需要顯示的數據集合,集合中一定要放置符合javabean風格的類的對象。
* 此方法支持的javabean屬性【數據類型有java基本數據類型及String,Date,byte[](圖片轉成位元組碼)】
*@paramout與輸出設備關聯的流對象,可以將EXCEL文檔導出到本地文件或者網路中
*@parampattern如果有時間數據,設定輸出格式。默認為"yyy-MM-dd"
*@throwsIOException
*/
publicstaticvoidexportExcel(Stringtitle,String[]headers,Collection<?>dataset,OutputStreamout,Stringpattern)throwsIOException{
//聲明一個工作薄
HSSFWorkbookworkbook=newHSSFWorkbook();
//生成一個表格
HSSFSheetsheet=workbook.createSheet(title);
//設置表格默認列寬度為15個位元組
sheet.setDefaultColumnWidth((short)20);
//生成一個樣式
HSSFCellStylestyle=workbook.createCellStyle();
//設置這些樣式
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//生成一個字體
HSSFFontfont=workbook.createFont();
font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short)12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//把字體應用到當前的樣式
style.setFont(font);
//生成並設置另一個樣式
HSSFCellStylestyle2=workbook.createCellStyle();
style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
//生成另一個字體
HSSFFontfont2=workbook.createFont();
font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
//把字體應用到當前的樣式
style2.setFont(font2);
//產生表格標題行
HSSFRowrow=sheet.createRow(0);
for(shorti=0;i<headers.length;i++){
HSSFCellcell=row.createCell(i);
cell.setCellStyle(style);
HSSFRichTextStringtext=newHSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
//遍歷集合數據,產生數據行
Iterator<?>it=dataset.iterator();
intindex=0;
while(it.hasNext()){
index++;
row=sheet.createRow(index);
Objectt=it.next();
//利用反射,根據javabean屬性的先後順序,動態調用getXxx()方法得到屬性值
Field[]fields=t.getClass().getDeclaredFields();
for(shorti=0;i<fields.length;i++){
HSSFCellcell=row.createCell(i);
cell.setCellStyle(style2);
Fieldfield=fields[i];
StringfieldName=field.getName();
StringgetMethodName="get"
+fieldName.substring(0,1).toUpperCase()
+fieldName.substring(1);//注意實體getSet不要自己改名字不然反射會有問題
try{
ClasstCls=t.getClass();
MethodgetMethod=tCls.getMethod(getMethodName,newClass[]{});
Objectvalue=getMethod.invoke(t,newObject[]{});
HSSFRichTextStringrichString=newHSSFRichTextString(value.toString());
HSSFFontfont3=workbook.createFont();
font3.setColor(HSSFColor.BLUE.index);
richString.applyFont(font3);
cell.setCellValue(richString);
}catch(SecurityExceptione){
e.printStackTrace();
e=null;
}catch(NoSuchMethodExceptione){
e.printStackTrace();
e=null;
}catch(IllegalArgumentExceptione){
e.printStackTrace();
e=null;
}catch(IllegalAccessExceptione){
e.printStackTrace();
e=null;
}catch(InvocationTargetExceptione){
e.printStackTrace();
e=null;
}finally{
//清理資源
}
}
}
try{
workbook.write(out);
}catch(IOExceptione){
e.printStackTrace();
e=null;
}
}
}

Ⅶ java導出excel

wb = Workbook.getWorkbook(file);//按路徑獲取抄excel表
Sheet sheet = wb.getSheet(0);//第一個工作簿
sheet.getCell(x,y).getContents())//獲取x列y行的數據;
需要一個jxl架包

Ⅷ java : 一個excel文件以二進制的形式存在資料庫中 如何將它導出並下載到本地

從資料庫中得到Blob/Clob,然後得到InputStream,直接給response.getOutputStream() 輸出就可以

閱讀全文

與java導出excel下載文件相關的資料

熱點內容
win10錯誤2系統找不到指定文件 瀏覽:327
U盤啟動載入資源文件失敗 瀏覽:459
怎樣把ug的pdf文件導入cad 瀏覽:148
c盤文件刪不了怎麼辦 瀏覽:248
win7無線網路禁用 瀏覽:455
如何把電腦文件夾圖片放置在一起 瀏覽:702
如何對訪談法進行數據分析 瀏覽:388
國土三調文件用什麼軟體什麼打開 瀏覽:651
數控銑床編程特點是什麼 瀏覽:119
飛鴿傳輸一次能傳多少文件 瀏覽:488
手機照片許可權怎麼設置密碼 瀏覽:341
es文件瀏覽器怎麼隱藏 瀏覽:649
刪除的文件為什麼恢復 瀏覽:314
血緣詛咒怎麼升級 瀏覽:604
文件分享到微信怎麼操作 瀏覽:393
tmx文件trados 瀏覽:704
大數據與會計選課怎麼選 瀏覽:684
網路的不穩定因素有哪些 瀏覽:950
獵豹瀏覽器javascript 瀏覽:723
哪個列印軟體保存數據時間長 瀏覽:873

友情鏈接