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

java導出excel文件名

發布時間:2023-05-26 08:56:33

1. java導出excel

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

2. 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>

3. java怎麼導出excel表格

可以使用POI開源的api:
1.首先下載poi-3.6-20091214.jar,下載地址如下:
http://download.csdn.net/detail/evangel_z/3895051

2.Student.java

import java.util.Date;

public class Student
{
private int id;
private String name;
private int age;
private Date birth;

public Student()
{
}

public Student(int id, String name, int age, Date birth)
{
this.id = id;
this.name = name;
this.age = age;
this.birth = birth;
}

public int getId()
{
return id;
}

public void setId(int id)
{
this.id = id;
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public int getAge()
{
return age;
}

public void setAge(int age)
{
this.age = age;
}

public Date getBirth()
{
return birth;
}

public void setBirth(Date birth)
{
this.birth = birth;
}

}
3.CreateSimpleExcelToDisk.java

import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class CreateSimpleExcelToDisk
{
/**
* @功能:手工構建一個簡單格式的Excel
*/
private static List<Student> getStudent() throws Exception
{
List list = new ArrayList();
SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");

Student user1 = new Student(1, "張三", 16, df.parse("1997-03-12"));
Student user2 = new Student(2, "李四", 17, df.parse("1996-08-12"));
Student user3 = new Student(3, "王五", 26, df.parse("1985-11-12"));
list.add(user1);
list.add(user2);
list.add(user3);

return list;
}

public static void main(String[] args) throws Exception
{
// 第一步,創建一個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();
}
}
}

4. 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

5. java 通用導出一個excel

java導出Excel通用方法,只需要一個list 集合。
package oa.common.utils;
import java.io.OutputStream;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import java.lang.reflect.Field;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
/***
* @author lsf
*/
public class ExportExcel {
/***************************************************************************
* @param fileName EXCEL文件名稱
* @param listTitle EXCEL文件第一行列標題集合
* @param listContent EXCEL文件正文數據集合
* @return
*/
public final static String exportExcel(String fileName,String[] Title, List<Object> listContent) {
String result="系統提示:Excel文件導出成功!";
// 以下開始輸出到EXCEL
try {
//定義輸出流,以便打開保存對話框______________________begin
HttpServletResponse response=ServletActionContext.getResponse();
OutputStream os = response.getOutputStream();// 取得輸出流
response.reset();// 清空輸出流
response.setHeader("Content-disposition", "attachment; filename="族賀+ new String(fileName.getBytes("GB2312"),"ISO8859-1"));
// 設定輸出文件模世頭
response.setContentType("application/msexcel");// 定義輸出類型
//定義輸出流,以便打開保存對話框_______________________end

/** **********創建工作簿************ */
WritableWorkbook workbook = Workbook.createWorkbook(os);

/** **********創建工作表************ */

WritableSheet sheet = workbook.createSheet("Sheet1", 0);

/** **********設置縱橫列印(默認旦穗肢為縱打)、列印紙***************** */
jxl.SheetSettings sheetset = sheet.getSettings();
sheetset.setProtected(false);

/** ************設置單元格字體************** */
WritableFont NormalFont = new WritableFont(WritableFont.ARIAL, 10);
WritableFont BoldFont = new WritableFont(WritableFont.ARIAL, 10,WritableFont.BOLD);

/** ************以下設置三種單元格樣式,靈活備用************ */
// 用於標題居中
WritableCellFormat wcf_center = new WritableCellFormat(BoldFont);
wcf_center.setBorder(Border.ALL, BorderLineStyle.THIN); // 線條
wcf_center.setVerticalAlignment(VerticalAlignment.CENTRE); // 文字垂直對齊
wcf_center.setAlignment(Alignment.CENTRE); // 文字水平對齊
wcf_center.setWrap(false); // 文字是否換行

// 用於正文居左
WritableCellFormat wcf_left = new WritableCellFormat(NormalFont);
wcf_left.setBorder(Border.NONE, BorderLineStyle.THIN); // 線條
wcf_left.setVerticalAlignment(VerticalAlignment.CENTRE); // 文字垂直對齊
wcf_left.setAlignment(Alignment.LEFT); // 文字水平對齊
wcf_left.setWrap(false); // 文字是否換行

/** ***************以下是EXCEL開頭大標題,暫時省略********************* */
//sheet.mergeCells(0, 0, colWidth, 0);
//sheet.addCell(new Label(0, 0, "XX報表", wcf_center));
/** ***************以下是EXCEL第一行列標題********************* */
for (int i = 0; i < Title.length; i++) {
sheet.addCell(new Label(i, 0,Title[i],wcf_center));
}
/** ***************以下是EXCEL正文數據********************* */
Field[] fields=null;
int i=1;
for(Object obj:listContent){
fields=obj.getClass().getDeclaredFields();
int j=0;
for(Field v:fields){
v.setAccessible(true);
Object va=v.get(obj);
if(va==null){
va="";
}
sheet.addCell(new Label(j, i,va.toString(),wcf_left));
j++;
}
i++;
}
/** **********將以上緩存中的內容寫到EXCEL文件中******** */
workbook.write();
/** *********關閉文件************* */
workbook.close();

} catch (Exception e) {
result="系統提示:Excel文件導出失敗,原因:"+ e.toString();
System.out.println(result);
e.printStackTrace();
}
return result;
}
}

測試:
/**
* 導出excel
* @return
*/
public String excelPage(){
ExportExcel excel=new ExportExcel();
String str="";
try {
str = new String(getHTTP.getRequest().getParameter("wineOrg.orgName").getBytes("iso8859-1"),"UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
wineOrg.setOrgName(str);
List<Object> li=service.exportExcel(wineOrg);
String[] Title={"機構ID","會員編號","類別","名稱","省ID","省名稱","城市ID","城市名稱","詳細地址","聯系人","性別","聯系手機","聯系電話","傳真","郵箱","QQ","生日","積分","客戶等級","現金賬戶余額","結算方式","客戶類型","購買次數","購買支數","創建人ID","創建人姓名","create_time","del","STS","備注","負責人ID","負責人姓名","審核標識","審核人ID ","審核人姓名","審核日期","分配人ID","分配人姓名","分配日期","修改人ID","修改人姓名 ","修改時間"};
excel.exportExcel("客戶資料信息.xls",Title, li);
return SUCCESS;
}

6. 如何導出生成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) { }
}

7. java開發怎麼導入導出excel裡面信息內容

publicclassExcelExport{
/**
*默認每個sheet頁最多顯示的行數
*/
privatestaticfinalintsheet_rows=50000;

/**
*導出Excel文件
*
*@paramtitleList
*表頭信息
*@paramdataList
*表格數據
*@paramfileName
*導出文件完整名稱demo.xls
*@paramrequest
*@paramresponse
*@throwsIOException
*/
(List<String>titleList,
List<List<String>>dataList,StringfileName,
HttpServletRequestrequest,HttpServletResponseresponse)
throwsIOException{
HSSFWorkbookworkBook=exportDataToExcel(titleList,dataList);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("UTF-8");
fileName=encodeFilename(fileName,request);
response.setHeader("Content-disposition","attachment;filename="+fileName);
workBook.write(response.getOutputStream());
response.getOutputStream().flush();
response.getOutputStream().close();
}

(Stringfilename,HttpServletRequestrequest){
Stringagent=request.getHeader("USER-AGENT");
try{
if((agent!=null)&&(0<=agent.indexOf("Firefox"))){
returnMimeUtility.encodeText(filename,"UTF-8","B");
}elseif((agent!=null)&&(0<=agent.indexOf("Chrome"))){

returnfilename=newString(filename.getBytes(),"ISO8859-1");
}
else{

if(agent!=null){

StringnewFileName=URLEncoder.encode(filename,"UTF-8");
newFileName=StringUtils.replace(newFileName,"+","%20");
if(newFileName.length()>150){
newFileName=newString(filename.getBytes("GB2312"),
"ISO8859-1");
newFileName=StringUtils.replace(newFileName,"",
"%20");
}
returnnewFileName;
}
}
}catch(Exceptionex){
returnfilename;
}
returnfilename;
}

(List<String>titleList,List<List<String>>dataList){

/*1.創建一個Excel文件*/
HSSFWorkbookworkbook=newHSSFWorkbook();
/*2.創建Excel的一個Sheet*/
HSSFSheetsheet=workbook.createSheet();
/*3.創建表頭凍結*/
sheet.createFreezePane(0,1);
/*4.設置列寬*/
for(inti=0;i<titleList.size();i++){
sheet.setColumnWidth(i,5000);
}
/*5.表頭字體*/
HSSFFontheadfont=workbook.createFont();
headfont.setFontName("宋體");
headfont.setFontHeightInPoints((short)12);//字體大小
headfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//加粗
/*6.表頭樣式*/
HSSFCellStyleheadstyle=workbook.createCellStyle();
headstyle.setFont(headfont);
headstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//左右居中
//設置背景色為藍色
headstyle.setFillForegroundColor(HSSFColor.LIGHT_BLUE.index);
headstyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

/*7.普通單元格字體*/
HSSFFontfont=workbook.createFont();
font.setFontName("宋體");
font.setFontHeightInPoints((short)12);
/*8.普通單元格樣式*/
HSSFCellStylestyle=workbook.createCellStyle();
style.setFont(font);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//左右居中
/*9.拼裝表頭*/
Iterator<String>titleRowIterator=titleList.iterator();
intcolumnIndex=0;
HSSFRowrow=sheet.createRow(0);
while(titleRowIterator.hasNext()){
StringcellValue=titleRowIterator.next();
HSSFCellcell=row.createCell(columnIndex);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(cellValue);
cell.setCellStyle(headstyle);
columnIndex++;
cell=null;
}
/*10.組織表數據*/
Iterator<List<String>>rowIterator=dataList.iterator();
introwIndex=1;
while(rowIterator.hasNext()){
List<String>columnList=rowIterator.next();
row=sheet.createRow(rowIndex);
Iterator<String>columnIterator=columnList.iterator();
columnIndex=0;
while(columnIterator.hasNext()){
StringcellValue=columnIterator.next();
HSSFCellcell=row.createCell(columnIndex);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(cellValue);
cell.setCellStyle(style);
cell=null;
columnIndex++;
}
row=null;
rowIndex++;
}
returnworkbook;
}

/**
*重載導出數據到Excel中
*@paramtitleList表頭
*@paramdataList表數據
*@paramamount每個sheet頁顯示行數
*@return
*/
(List<String>titleList,List<List<String>>dataList,intamount){

/*1.創建一個Excel文件*/
HSSFWorkbookworkbook=newHSSFWorkbook();

//校驗傳入的參數
if(titleList==null){
titleList=newArrayList<String>();
}
//無數據直接返回
if(dataList==null||dataList.size()==0){
returnworkbook;
}
//傳入數據不正確,按照默認條數顯示
if(amount>65535||amount<=0){
amount=sheet_rows;
}

//獲取sheet頁的數量
introw_num=0;
inty=dataList.size()%amount;
if(y==0){
row_num=dataList.size()/amount;
}else{
row_num=dataList.size()/amount+1;
}

/*表頭字體*/
HSSFFontheadfont=workbook.createFont();
headfont.setFontName("宋體");
headfont.setFontHeightInPoints((short)12);//字體大小
headfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//加粗
/*表頭樣式*/
HSSFCellStyleheadstyle=workbook.createCellStyle();
headstyle.setFont(headfont);
headstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//左右居中
//設置背景色為藍色
headstyle.setFillForegroundColor(HSSFColor.LIGHT_BLUE.index);
headstyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

/*普通單元格字體*/
HSSFFontfont=workbook.createFont();
font.setFontName("宋體");
font.setFontHeightInPoints((short)12);
/*普通單元格樣式*/
HSSFCellStylestyle=workbook.createCellStyle();
style.setFont(font);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//左右居中

//循環寫入每個sheet頁
for(inti=0;i<row_num;i++){
/*創建Excel的一個Sheet*/
HSSFSheetsheet=workbook.createSheet();
/*創建表頭凍結*/
sheet.createFreezePane(0,1);
/*設置列寬*/
for(intt=0;t<titleList.size();t++){
sheet.setColumnWidth(t,5000);
}
/*拼裝表頭*/
Iterator<String>titleRowIterator=titleList.iterator();
intcolumnIndex=0;
HSSFRowrow=sheet.createRow(0);
while(titleRowIterator.hasNext()){
StringcellValue=titleRowIterator.next();
HSSFCellcell=row.createCell(columnIndex);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(cellValue);
cell.setCellStyle(headstyle);
columnIndex++;
cell=null;
}
/*組織表數據*/
introwIndex=1;
for(intj=amount*i;(j<amount*(i+1)&&j<dataList.size());j++){
List<String>columnList=dataList.get(j);
row=sheet.createRow(rowIndex);
Iterator<String>columnIterator=columnList.iterator();
columnIndex=0;
while(columnIterator.hasNext()){
StringcellValue=columnIterator.next();
HSSFCellcell=row.createCell(columnIndex);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(cellValue);
cell.setCellStyle(style);
cell=null;
columnIndex++;
}
row=null;
rowIndex++;
}
}
returnworkbook;
}

/**
*重載導出Excel功能,新增一項amount每個sheet導出記錄行數
*@paramtitleList
*@paramdataList
*@paramfileName
*@paramamount行數如果小於等於0或大於65535則按照默認顯示
*@paramrequest
*@paramresponse
*@throwsIOException
*/
(List<String>titleList,
List<List<String>>dataList,StringfileName,intamount,
HttpServletRequestrequest,HttpServletResponseresponse)
throwsIOException{
HSSFWorkbookworkBook=exportDataToExcel(titleList,dataList,amount);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("UTF-8");
fileName=encodeFilename(fileName,request);
response.setHeader("Content-disposition","attachment;filename="+fileName);
workBook.write(response.getOutputStream());
response.getOutputStream().flush();
response.getOutputStream().close();
}

}

說明:main方法里的第一個參數為要導出的表頭信息,
第二個參數為數據信息,
第三個參數設置文件名,設置好以後直接調用就可以導出Excle了;

導入就是把文件存到伺服器,可用Mogodb等資料庫存儲,以下是讀取已存根據存儲的文件id解析Excle數據的大致過程:

POIFSFileSystemfs=null;
if(!StringUtils.isBlank(fileId)){
fs=newPOIFSFileSystem(newByteArrayInputStream(
//傳入對應的文件對象
MongoFileUtil.readFile(fileId)));
}
//構造XSSFWorkbook對象,filePath傳入文件路徑
HSSFWorkbookxwb=newHSSFWorkbook(fs);
//讀取第一個sheet
HSSFSheetsheet=xwb.getSheetAt(0);


for(inti=sheet.getFirstRowNum()+1;i<sheet.getPhysicalNumberOfRows();i++){
//解析每行的數據
HSSFRowsingleRow=sheet.getRow(i);
//解析每個單元格數據
singleRow.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
StringcellValue=singleRow.getCell(0).getStringCellValue();
}

8. Java導出Excel,文件名為"XXX單-2018-10-26 09_01_43.xls",怎麼把時分秒的間隔 _ 變成:呢

你的語句是對的,只是冒號不可以作為文件名的,建議還是用下劃線吧。

9. 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]);
}

}
}

10. java怎麼實現導出excel

import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class CreateSimpleExcelToDisk
{
/**
* @功能:手工構建一個簡單格式的Excel
*/
private static List<Student> getStudent() throws Exception
{
List list = new ArrayList();
SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");

Student user1 = new Student(1, "張三", 16, df.parse("1997-03-12"));
Student user2 = new Student(2, "李四", 17, df.parse("1996-08-12"));
Student user3 = new Student(3, "王五", 26, df.parse("1985-11-12"));
list.add(user1);
list.add(user2);
list.add(user3);

return list;
}

public static void main(String[] args) throws Exception
{
// 第一步,創建一個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();
}
}
}

閱讀全文

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

熱點內容
網易嚴選微信app怎麼退出 瀏覽:892
a標簽文件下載 瀏覽:298
手柄連接驅動程序 瀏覽:442
中國資料庫發展研討會 瀏覽:415
win7去掉登錄密碼 瀏覽:38
imacappleid 瀏覽:560
網易郵箱怎麼發文件手機app 瀏覽:325
如何快速升級考拉 瀏覽:745
編程加入高考需要什麼條件 瀏覽:602
小米手機怎麼同步舊手機app的數據 瀏覽:253
cad版本不同會顯示外來文件嗎 瀏覽:538
卸載ps提示有正在使用的文件 瀏覽:165
忘記路由器wifi密碼 瀏覽:390
5s升級103 瀏覽:140
博圖v13上載程序 瀏覽:142
有什麼夜晚網站 瀏覽:115
win10環境配置在哪個文件夾 瀏覽:949
文件王測試視頻 瀏覽:874
易語言圖片框顯示文件夾的相片 瀏覽:211
如何通過數據網路發簡訊 瀏覽:423

友情鏈接