導航:首頁 > 編程語言 > java導出

java導出

發布時間:2022-01-15 00:03:49

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)

// 創建臨時文件(excel為Workbook對象)
response.reset();
response.setContentType("application/download");
response.setHeader("Content-Disposition",
"attachment;filename=" + excel.getFileName());
excel.getExcel().write(response.getOutputStream());
response.flushBuffer();

❸ 請問下java中導出圖片怎麼做

很簡單的啦,bufferedimage啦你去看看jdk的demo吧

❹ java導出 提示導出成功信息

java:
request.setAttribute("Msg", "成功導出3條記錄");
導出後載入的頁面:
<%
String message = request.getAttribute("Msg")==null?"":request.getAttribute("Msg").toString();
%>

<script language="javascript">
var msg1 = "<%=message%>";
if(msg1 != '')
alert(msg1);
<%}%>
這是腳本彈出式提示.不知是否你想要的,也可改成頁面中顯示,不用彈出的.

❺ 怎麼用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的幾種方法的比較

Excel的兩種導出入門方法(JAVA與JS)

最近在做一個小項目作為練手,其中使用到了導出到Excel表格,一開始做的是使用JAVA的POI導出的,但因為我的數據是爬蟲爬出來的,數據暫時並不保存在資料庫或後台,所以直接顯示在HTML的table,需要下載時又要將數據傳回後台然後生成Excel文件,最後再從伺服器下載到本地,過程幾度經過網路傳輸,感覺比較耗時與浪費性能,於是想著在HTML中的Table直接導到Excel中節約資源

JAVA導出EXCEL(.xls)

導出Excel用的插件是apache的poi.jar,maven地址如下

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version></dependency>

1. 簡單應用

先來個簡化無樣式的Excel導出,由於我的數據存在JSON中,所以形參是JSONArray,朋友們根據自己的實際數據類型(Map,List,Set等)傳入即可 ,代碼如下

/**
* 創建excel並填入數據
* @author LiQuanhui
* @date 2017年11月24日 下午5:25:13
* @param head 數據頭
* @param body 主體數據
* @return HSSFWorkbook
*/
public static HSSFWorkbook expExcel(JSONArray head, JSONArray body) { //創建一個excel工作簿
HSSFWorkbook workbook = new HSSFWorkbook(); //創建一個sheet工作表
HSSFSheet sheet = workbook.createSheet("學生信息");
//創建第0行表頭,再在這行里在創建單元格,並賦值
HSSFRow row = sheet.createRow(0);
HSSFCell cell = null; for (int i = 0; i < head.size(); i++) {
cell = row.createCell(i);
cell.setCellValue(head.getString(i));//設置值
}
//將主體數據填入Excel中
for (int i = 0, isize = body.size(); i < isize; i++) {
row = sheet.createRow(i + 1);
JSONArray stuInfo = body.getJSONArray(i); for (int j = 0, jsize = stuInfo.size(); j < jsize; j++) {
cell = row.createCell(j);
cell.setCellValue(stuInfo.getString(j));//設置值
}
} return workbook;
}

創建好Excel對象並填好值後(就是得到workbook),就是將這個對象以文件流的形式輸出到本地上去,代碼如下

/**
* 文件輸出
* @author LiQuanhui
* @date 2017年11月24日 下午5:26:23
* @param workbook 填充好的workbook
* @param path 存放的位置
*/
public static void outFile(HSSFWorkbook workbook,String path) {
OutputStream os=null; try {
os = new FileOutputStream(new File(path));
workbook.write(os);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}

至此Excel的導出其實已經做完了。

2. 添加樣式後導出

但通常這並不能滿足我們的需求,因為通常是需要設置Excel的一些樣式的,如字體、居中等等,設置單元格樣式主要用到這個類(HSSFCellStyle)

HSSFCellStyle cellStyle = workbook.createCellStyle();

現在說說HSSFCellStyle都能幹些什麼

HSSFCellStyle cellStyle = workbook.createCellStyle();//創建單元格樣式對象1.設置字體
HSSFFont font = workbook.createFont(); //font.setFontHeight((short)12);//這個設置字體會很大
font.setFontHeightInPoints((short)12);//這才是我們平常在Excel設置字體的值
font.setFontName("黑體");//字體:宋體、華文行楷等等
cellStyle.setFont(font);//將該字體設置進去2.設置對齊方式
cellStyle.setAlignment(horizontalAlignment);//horizontalAlignment參考下面給出的參數
//以下是最常用的三種對齊分別是居中,居左,居右,其餘的寫代碼的時候按提示工具查看即可
HorizontalAlignment.CENTER
HorizontalAlignment.LEFT
HorizontalAlignment.RIGHT3.設置邊框
cellStyle.setBorderBottom(border); // 下邊框
cellStyle.setBorderLeft(border);// 左邊框
cellStyle.setBorderTop(border);// 上邊框
cellStyle.setBorderRight(border);// 右邊框
//border的常用參數如下
BorderStyle.NONE 無邊框
BorderStyle.THIN 細邊框
BorderStyle.MEDIUM 中等粗邊框
BorderStyle.THICK 粗邊框//其餘的我也描述不清是什麼形狀,有興趣的到時可以直接測試

在經過一系列的添加樣式之後,最後就會給單元格設置樣式

cell.setCellStyle(cellStyle);

3. 自動調整列寬

sheet.autoSizeColumn(i);//i為第幾列,需要全文都單元格居中的話,需要遍歷所有的列數

4. 完整的案例

public class ExcelUtils { /**
* 創建excel並填入數據
* @author LiQuanhui
* @date 2017年11月24日 下午5:25:13
* @param head 數據頭
* @param body 主體數據
* @return HSSFWorkbook
*/
public static HSSFWorkbook expExcel(JSONArray head, JSONArray body) {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("學生信息");

HSSFRow row = sheet.createRow(0);
HSSFCell cell = null;

HSSFCellStyle cellStyle = workbook.createCellStyle();
setBorderStyle(cellStyle, BorderStyle.THIN);
cellStyle.setFont(setFontStyle(workbook, "黑體", (short) 14));
cellStyle.setAlignment(HorizontalAlignment.CENTER);
for (int i = 0; i < head.size(); i++) {
cell = row.createCell(i);
cell.setCellValue(head.getString(i));
cell.setCellStyle(cellStyle);
}

HSSFCellStyle cellStyle2 = workbook.createCellStyle();
setBorderStyle(cellStyle2, BorderStyle.THIN);
cellStyle2.setFont(setFontStyle(workbook, "宋體", (short) 12));
cellStyle2.setAlignment(HorizontalAlignment.CENTER); for (int i = 0, isize = body.size(); i < isize; i++) {
row = sheet.createRow(i + 1);
JSONArray stuInfo = body.getJSONArray(i); for (int j = 0, jsize = stuInfo.size(); j < jsize; j++) {
cell = row.createCell(j);
cell.setCellValue(stuInfo.getString(j));
cell.setCellStyle(cellStyle2);
}
} for (int i = 0, isize = head.size(); i < isize; i++) {
sheet.autoSizeColumn(i);
} return workbook;
} /**
* 文件輸出
* @author LiQuanhui
* @date 2017年11月24日 下午5:26:23
* @param workbook 填充好的workbook
* @param path 存放的位置
*/
public static void outFile(HSSFWorkbook workbook,String path) {
OutputStream os=null; try {
os = new FileOutputStream(new File(path));
workbook.write(os);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
} /**
* 設置字體樣式
* @author LiQuanhui
* @date 2017年11月24日 下午3:27:03
* @param workbook 工作簿
* @param name 字體類型
* @param height 字體大小
* @return HSSFFont
*/
private static HSSFFont setFontStyle(HSSFWorkbook workbook, String name, short height) {
HSSFFont font = workbook.createFont();
font.setFontHeightInPoints(height);
font.setFontName(name); return font;
} /**
* 設置單元格樣式
* @author LiQuanhui
* @date 2017年11月24日 下午3:26:24
* @param workbook 工作簿
* @param border border樣式
*/
private static void setBorderStyle(HSSFCellStyle cellStyle, BorderStyle border) {
cellStyle.setBorderBottom(border); // 下邊框
cellStyle.setBorderLeft(border);// 左邊框
cellStyle.setBorderTop(border);// 上邊框
cellStyle.setBorderRight(border);// 右邊框
}
}

POI的功能其實還是很強大的,這里只介紹了Excel的一丁點皮毛給入門的查看,如果想對Excel進行更多的設置可以查看下面的這篇文章,有著大量的使用說明。
空谷幽瀾的POI使用詳解

JS導出EXCEL(.xls)

java的Excel導出提供了強大的功能,但也對伺服器造成了一定資源消耗,若能使用客戶端的資源那真是太好了

1. 簡單應用

JS的導出Excel非常簡單,只需要引用Jquery和tableExport.js並設置一個屬性即可

<script src="<%=basePath%>/static/js/tableExport.js" type="text/javascript"></script><script type="text/javascript">
function exportExcelWithJS(){ //獲取要導出Excel的表格對象並設置tableExport方法,設置導出類型type為excel
$('#tableId').tableExport({ type:'excel'
});
}</script><button class="btn btn-primary" type="button" style="float: right;" onclick="exportExcelWithJS()">下載本表格</button>

JS的導出就完成了,是不是特別簡單

2. 進階應用

但上面僅僅是個簡單的全表無樣式的導出
這tableExport.js還有一些其他功能,忽略行,忽略列,設置樣式等,屬性如下

<script type="text/javascript">
function exportExcelWithJS(){ //獲取要導出Excel的表格對象並設置tableExport方法,設置導出類型type為excel
$('#tableId').tableExport({ type:'excel',//導出為excel
fileName:'2017工資表',//文件名
worksheetName:'11月工資',//sheet表的名字
ignoreColumn:[0,1,2],//忽略的列,從0開始算
ignoreRow:[2,4,5],//忽略的行,從0開始算
excelstyles:['text-align']//使用樣式,不用填值只寫屬性,值讀取的是html中的
});
}</script>

❼ java項目怎樣導出

第一步:選中項目;
第二步:右擊滑鼠,選中「export」,之後選擇需要的導出類型;
第三步:選擇「Browse」,選擇導出路徑;
第四步:選擇「Finsh」即可完成導出。
備註:第二步中的導出類型根據實際需要選擇即可,如war(web項目,部署到tomcat等容器運行,)、runnable jar(可運行jar包),JarFile(作為單獨的jar包,之後放到需要的項目的lib下)等,這個根據實際需要選擇即可。

❽ 編寫好的JAVA程序如何導出保存並運行

首先,你需要在記事本中寫一個「你好,下午好」的程序。

❾ 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 */

❿ java中導出到Excel

java中jxl導出數據到excel的例子
import jxl.*;
import jxl.write.*;
import java.io.*;
import java.io.File.*;
import java.util.*;

public class excel
{
public static void main(String[] args)
{

String targetfile = "c:/out.xls";//輸出的excel文件名
String worksheet = "List";//輸出的excel文件工作表名
String[] title = {"ID","NAME","DESCRIB"};//excel工作表的標題

WritableWorkbook workbook;
try
{
//創建可寫入的Excel工作薄,運行生成的文件在tomcat/bin下
//workbook = Workbook.createWorkbook(new File("output.xls"));
System.out.println("begin");

OutputStream os=new FileOutputStream(targetfile);
workbook=Workbook.createWorkbook(os);

WritableSheet sheet = workbook.createSheet(worksheet, 0); //添加第一個工作表
//WritableSheet sheet1 = workbook.createSheet("MySheet1", 1); //可添加第二個工作
/*
jxl.write.Label label = new jxl.write.Label(0, 2, "A label record"); //put a label in cell A3, Label(column,row)
sheet.addCell(label);
*/

jxl.write.Label label;
for (int i=0; i<title.length; i++)
{
//Label(列號,行號 ,內容 )
label = new jxl.write.Label(i, 0, title[i]); //put the title in row1
sheet.addCell(label);
}

//下列添加的對字體等的設置均調試通過,可作參考用

//添加數字
jxl.write.Number number = new jxl.write.Number(3, 4, 3.14159); //put the number 3.14159 in cell D5
sheet.addCell(number);

//添加帶有字型Formatting的對象
jxl.write.WritableFont wf = new jxl.write.WritableFont(WritableFont.TIMES,10,WritableFont.BOLD,true);
jxl.write.WritableCellFormat wcfF = new jxl.write.WritableCellFormat(wf);
jxl.write.Label labelCF = new jxl.write.Label(4,4,"文本",wcfF);
sheet.addCell(labelCF);

//添加帶有字體顏色,帶背景顏色 Formatting的對象
jxl.write.WritableFont wfc = new jxl.write.WritableFont(WritableFont.ARIAL,10,WritableFont.BOLD,false,jxl.format.UnderlineStyle.NO_UNDERLINE,jxl.format.Colour.RED);
jxl.write.WritableCellFormat wcfFC = new jxl.write.WritableCellFormat(wfc);
wcfFC.setBackground(jxl.format.Colour.BLUE);
jxl.write.Label labelCFC = new jxl.write.Label(1,5,"帶顏色",wcfFC);
sheet.addCell(labelCFC);

//添加帶有formatting的Number對象
jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#.##");
jxl.write.WritableCellFormat wcfN = new jxl.write.WritableCellFormat(nf);
jxl.write.Number labelNF = new jxl.write.Number(1,1,3.1415926,wcfN);
sheet.addCell(labelNF);

//3.添加Boolean對象
jxl.write.Boolean labelB = new jxl.write.Boolean(0,2,false);
sheet.addCell(labelB);

//4.添加DateTime對象
jxl.write.DateTime labelDT = new jxl.write.DateTime(0,3,new java.util.Date());
sheet.addCell(labelDT);

//添加帶有formatting的DateFormat對象
jxl.write.DateFormat df = new jxl.write.DateFormat("ddMMyyyyhh:mm:ss");
jxl.write.WritableCellFormat wcfDF = new jxl.write.WritableCellFormat(df);
jxl.write.DateTime labelDTF = new jxl.write.DateTime(1,3,new java.util.Date(),wcfDF);
sheet.addCell(labelDTF);

//和賓單元格
//sheet.mergeCells(int col1,int row1,int col2,int row2);//左上角到右下角
sheet.mergeCells(4,5,8,10);//左上角到右下角
wfc = new jxl.write.WritableFont(WritableFont.ARIAL,40,WritableFont.BOLD,false,jxl.format.UnderlineStyle.NO_UNDERLINE,jxl.format.Colour.GREEN);
jxl.write.WritableCellFormat wchB = new jxl.write.WritableCellFormat(wfc);
wchB.setAlignment(jxl.format.Alignment.CENTRE);
labelCFC = new jxl.write.Label(4,5,"單元合並",wchB);
sheet.addCell(labelCFC); //

//設置邊框
jxl.write.WritableCellFormat wcsB = new jxl.write.WritableCellFormat();
wcsB.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THICK);
labelCFC = new jxl.write.Label(0,6,"邊框設置",wcsB);
sheet.addCell(labelCFC);
workbook.write();
workbook.close();
}catch(Exception e)
{
e.printStackTrace();
}
System.out.println("end");
Runtime r=Runtime.getRuntime();
Process p=null;
//String cmd[]={"notepad","exec.java"};
String cmd[]={"C:\\Program Files\\Microsoft Office\\Office\\EXCEL.EXE","out.xls"};
try{
p=r.exec(cmd);
}
catch(Exception e){
System.out.println("error executing: "+cmd[0]);
}

}
}

閱讀全文

與java導出相關的資料

熱點內容
華為手機為什麼不升級安卓11 瀏覽:42
linuxrpm卸載jdk 瀏覽:860
mysql許可權設置命令 瀏覽:618
hexophp 瀏覽:271
用什麼app買東西半價 瀏覽:62
蘋果下載的pdf文件怎麼打開 瀏覽:211
如何在伺服器上隱藏源站地址 瀏覽:645
單片機進制字母對應表 瀏覽:528
向某人下命令 瀏覽:627
編程中刪除數組中的數 瀏覽:86
aes對稱加密反編譯 瀏覽:550
java編譯成exe 瀏覽:190
gps處理演算法 瀏覽:596
什麼app可以和對象存錢 瀏覽:146
java字元串表達式計算 瀏覽:330
javacmd環境變數 瀏覽:51
電視上面找不到全民歌app怎麼辦 瀏覽:156
單片機中psw0 瀏覽:994
優酷視頻加密么 瀏覽:763
本地連接dos命令 瀏覽:206