當前位置:首頁 » 編程語言 » javaexcel表格

javaexcel表格

發布時間: 2022-12-31 18:01:39

1. java中輸入輸出流如何把數據輸出為Excel表格形式

實現代碼如下:

import org.apache.poi.hssf.usermodel.*;

import java.io.FileOutputStream;

import java.io.IOException;

publicclass CreateCells

{

publicstaticvoid main(String[] args)

throws IOException

{

HSSFWorkbook wb = new HSSFWorkbook();//建立新HSSFWorkbook對象

HSSFSheet sheet = wb.createSheet("new sheet");//建立新的sheet對象

// Create a row and put some cells in it. Rows are 0 based.

HSSFRow row = sheet.createRow((short)0);//建立新行

// Create a cell and put a value in it.

HSSFCell cell = row.createCell((short)0);//建立新cell

cell.setCellValue(1);//設置cell的整數類型的值

// Or do it on one line.

row.createCell((short)1).setCellValue(1.2);//設置cell浮點類型的值

row.createCell((short)2).setCellValue("test");//設置cell字元類型的值

row.createCell((short)3).setCellValue(true);//設置cell布爾類型的值

HSSFCellStyle cellStyle = wb.createCellStyle();//建立新的cell樣式

cellStyle.setDataFormat(HSSFDataFormat.getFormat("m/d/yy h:mm"));//設置cell樣式為定製的日期格式

HSSFCell dCell =row.createCell((short)4);

dCell.setCellValue(new Date());//設置cell為日期類型的值

dCell.setCellStyle(cellStyle); //設置該cell日期的顯示格式

HSSFCell csCell =row.createCell((short)5);

csCell.setEncoding(HSSFCell.ENCODING_UTF_16);//設置cell編碼解決中文高位位元組截斷

csCell.setCellValue("中文測試_Chinese Words Test");//設置中西文結合字元串

row.createCell((short)6).setCellType(HSSFCell.CELL_TYPE_ERROR);//建立錯誤cell

// Write the output to a file

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

wb.write(fileOut);

fileOut.close();

}

}

2. 如何將java數據轉換成Excel表格

package common.util;

import jxl.*;
import jxl.format.UnderlineStyle;
import jxl.write.*;
import jxl.write.Number;
import jxl.write.Boolean;

import java.io.*;

/**
* Created by IntelliJ IDEA.
* User: xl
* Date: 2005-7-17
* Time: 9:33:22
* To change this template use File | Settings | File Templates.
*/
public class ExcelHandle
{
public ExcelHandle()
{
}

/**
* 讀取Excel
*
* @param filePath
*/
public static void readExcel(String filePath)
{
try
{
InputStream is = new FileInputStream(filePath);
Workbook rwb = Workbook.getWorkbook(is);
//Sheet st = rwb.getSheet("0")這里有兩種方法獲取sheet表,1為名字,而為下標,從0開始
Sheet st = rwb.getSheet("original");
Cell c00 = st.getCell(0,0);
//通用的獲取cell值的方式,返回字元串
String strc00 = c00.getContents();
//獲得cell具體類型值的方式
if(c00.getType() == CellType.LABEL)
{
LabelCell labelc00 = (LabelCell)c00;
strc00 = labelc00.getString();
}
//輸出
System.out.println(strc00);
//關閉
rwb.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}

/**
* 輸出Excel
*
* @param os
*/
public static void writeExcel(OutputStream os)
{
try
{
/**
* 只能通過API提供的工廠方法來創建Workbook,而不能使用WritableWorkbook的構造函數,
* 因為類WritableWorkbook的構造函數為protected類型
* method(1)直接從目標文件中讀取WritableWorkbook wwb = Workbook.createWorkbook(new File(targetfile));
* method(2)如下實例所示 將WritableWorkbook直接寫入到輸出流

*/
WritableWorkbook wwb = Workbook.createWorkbook(os);
//創建Excel工作表 指定名稱和位置
WritableSheet ws = wwb.createSheet("Test Sheet 1",0);

//**************往工作表中添加數據*****************

//1.添加Label對象
Label label = new Label(0,0,"this is a label test");
ws.addCell(label);

//添加帶有字型Formatting對象
WritableFont wf = new WritableFont(WritableFont.TIMES,18,WritableFont.BOLD,true);
WritableCellFormat wcf = new WritableCellFormat(wf);
Label labelcf = new Label(1,0,"this is a label test",wcf);
ws.addCell(labelcf);

//添加帶有字體顏色的Formatting對象
WritableFont wfc = new WritableFont(WritableFont.ARIAL,10,WritableFont.NO_BOLD,false,
UnderlineStyle.NO_UNDERLINE,jxl.format.Colour.RED);
WritableCellFormat wcfFC = new WritableCellFormat(wfc);
Label labelCF = new Label(1,0,"This is a Label Cell",wcfFC);
ws.addCell(labelCF);

//2.添加Number對象
Number labelN = new Number(0,1,3.1415926);
ws.addCell(labelN);

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

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

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

//添加帶有formatting的DateFormat對象
DateFormat df = new DateFormat("dd MM yyyy hh:mm:ss");
WritableCellFormat wcfDF = new WritableCellFormat(df);
DateTime labelDTF = new DateTime(1,3,new java.util.Date(),wcfDF);
ws.addCell(labelDTF);

//添加圖片對象,jxl只支持png格式圖片
File image = new File("f:\\2.png");
WritableImage wimage = new WritableImage(0,1,2,2,image);
ws.addImage(wimage);
//寫入工作表
wwb.write();
wwb.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}

/**
* 拷貝後,進行修改,其中file1為被對象,file2為修改後創建的對象
* 盡單元格原有的格式化修飾是不能去掉的,我們還是可以將新的單元格修飾加上去,
* 以使單元格的內容以不同的形式表現
* @param file1
* @param file2
*/
public static void modifyExcel(File file1,File file2)
{
try
{
Workbook rwb = Workbook.getWorkbook(file1);
WritableWorkbook wwb = Workbook.createWorkbook(file2,rwb);//
WritableSheet ws = wwb.getSheet(0);
WritableCell wc = ws.getWritableCell(0,0);
//判斷單元格的類型,做出相應的轉換
if(wc.getType == CellType.LABEL)
{
Label label = (Label)wc;
label.setString("The value has been modified");
}
wwb.write();
wwb.close();
rwb.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}

//測試
public static void main(String[] args)
{
try
{
//讀Excel
ExcelHandle.readExcel("f:/testRead.xls");
//輸出Excel
File fileWrite = new File("f:/testWrite.xls");
fileWrite.createNewFile();
OutputStream os = new FileOutputStream(fileWrite);
ExcelHandle.writeExcel(os);
//修改Excel
ExcelHandle.modifyExcel(new file(""),new File(""));
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

3. 如何在Java中導入Excel表數據

1,加入依賴的罐子文件:
引用:
*mysql的jar文件
*Spring_HOME/lib/poi/*.jar

2,編寫資料庫鏈接類
package com.zzg.db;
import java.sql.Connection;
import java.sql.DriverManager;
public class DbUtils {
private static Connection conn;

static {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/test","root","123456");
} catch (Exception e) {
e.printStackTrace();
}
}

public static Connection getConn() {
return conn;
}

public static void setConn(Connection conn) {
DbUtils.conn = conn;
}
}

3,編寫資料庫操作類

package com.zzg.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class ExcuteData {
private PreparedStatement pstmt;
public boolean ExcuData(String sql) {
Connection conn = DbUtils.getConn();
boolean flag=false;
try {
pstmt = conn.prepareStatement(sql);
flag=pstmt.execute();
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
}

4,編寫的Excel表格實體類

package com.zzg.model;
public class TableCell {
private String _name;
private String _value;
public String get_name() {
return _name;
}
public void set_name(String _name) {
this._name = _name;
}
public String get_value() {
return _value;
}
public void set_value(String _value) {
this._value = _value;
}
}

5,編寫主鍵生成方法

package com.zzg.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
public class GenericUtil {
public static String getPrimaryKey()
{
String primaryKey;
primaryKey = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
Random r = new Random();
primaryKey +=r.nextInt(100000)+100000;
return primaryKey;
}
}

6,編寫的Excel操作類

package com.zzg.deployData;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
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;
import com.zzg.db.ExcuteData;
import com.zzg.model.TableCell;
import com.zzg.util.GenericUtil;
public class OperExcel<T extends Serializable> {
private HSSFWorkbook workbook;
private String tableName;
private Class<T> type;
private String sheetName;

public OperExcel(File excelFile, String tableName, Class<T> type,
String sheetName) throws FileNotFoundException,
IOException {
workbook = new HSSFWorkbook(new FileInputStream(excelFile));
this.tableName = tableName;
this.type = type;
this.sheetName = sheetName;
InsertData();
}

// 向表中寫入數據
public void InsertData() {
System.out.println("yyy");
ExcuteData excuteData = new ExcuteData();
List<List> datas = getDatasInSheet(this.sheetName);
// 向表中添加數據之前先刪除表中數據
String strSql = "delete from " + this.tableName;
excuteData.ExcuData(strSql);
// 拼接sql語句
for (int i = 1; i < datas.size(); i++) {
strSql = "insert into " + this.tableName + "(";
List row = datas.get(i);
for (short n = 0; n < row.size(); n++) {
TableCell excel = (TableCell) row.get(n);
if (n != row.size() - 1)
strSql += excel.get_name() + ",";
else
strSql += excel.get_name() + ")";
}
strSql += " values (";
for (short n = 0; n < row.size(); n++) {
TableCell excel = (TableCell) row.get(n);
try {
if (n != row.size() - 1) {
strSql += getTypeChangeValue(excel) + ",";
} else
strSql += getTypeChangeValue(excel) + ")";
} catch (RuntimeException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//執行sql
excuteData.ExcuData(strSql);
}
}

/**
* 獲得表中的數據
* @param sheetName 表格索引(EXCEL 是多表文檔,所以需要輸入表索引號)
* @return 由LIST構成的行和表
*/
public List<List> getDatasInSheet(String sheetName) {
List<List> result = new ArrayList<List>();
// 獲得指定的表
HSSFSheet sheet = workbook.getSheet(sheetName);
// 獲得數據總行數
int rowCount = sheet.getLastRowNum();
if (rowCount < 1) {
return result;
}
// 逐行讀取數據
for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) {
// 獲得行對象
HSSFRow row = sheet.getRow(rowIndex);
if (row != null) {
List<TableCell> rowData = new ArrayList<TableCell>();
// 獲得本行中單元格的個數
int columnCount = sheet.getRow(0).getLastCellNum();
// 獲得本行中各單元格中的數據
for (short columnIndex = 0; columnIndex < columnCount; columnIndex++) {
HSSFCell cell = row.getCell(columnIndex);
// 獲得指定單元格中數據
Object cellStr = this.getCellString(cell);
TableCell TableCell = new TableCell();
TableCell.set_name(getCellString(
sheet.getRow(0).getCell(columnIndex)).toString());
TableCell.set_value(cellStr == null ? "" : cellStr
.toString());
rowData.add(TableCell);
}
result.add(rowData);
}
}
return result;
}

/**
* 獲得單元格中的內容
* @param cell
* @return result
*/
protected Object getCellString(HSSFCell cell) {
Object result = null;
if (cell != null) {
int cellType = cell.getCellType();
switch (cellType) {

case HSSFCell.CELL_TYPE_STRING:
result = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
result = cell.getNumericCellValue();
break;
case HSSFCell.CELL_TYPE_FORMULA:
result = cell.getNumericCellValue();
break;
case HSSFCell.CELL_TYPE_ERROR:
result = null;
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
result = cell.getBooleanCellValue();
break;
case HSSFCell.CELL_TYPE_BLANK:
result = null;
break;
}
}
return result;
}

// 根據類型返回相應的值
@SuppressWarnings("unchecked")
public String getTypeChangeValue(TableCell excelElement)
throws RuntimeException, Exception {
String colName = excelElement.get_name();
String colValue = excelElement.get_value();
String retValue = "";
if (colName.equals("id")) {
retValue = "'" + GenericUtil.getPrimaryKey() + "'";
return retValue;
}
if (colName == null) {
retValue = null;
}
if (colName.equals("class_createuser")) {
retValue = "yaa101";
return "'" + retValue + "'";
}
retValue = "'" + colValue + "'";
return retValue;
}
}

7,編寫調用操作的Excel類的方法

package com.zzg.deployData;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
public class DeployData {
private File fileOut;
public void excute(String filepath) {
fileOut = new File(filepath);
this.deployUserInfoData();
}

public void deployUserInfoData() {
try {
new OperExcel(fileOut, "test", Object.class, "Sheet1");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

8,編寫客戶端
package com.zzg.client;
import com.zzg.deployData.DeployData;
public class DeployClient {
public static void main(String[] args) {
DeployData deployData = new DeployData();
deployData.excute("D://test.xls");
}
}

4. 用java讀取Excel表格

下個jxl.jar;看看aip就能用了

5. java怎麼將excel表格數據導入資料庫

excel有行和列,可以對應資料庫表的行和欄位。先獲取你excel中的數據,如果你的數據是和java中實體對應的話,循環獲取每一行數據存放進實體對象中,然後進行資料庫保存就好了。
讀取excel數據可以使用poi。

6. 如何用JAVA把EXCEL表格讀出來(不用資料庫)

public class Excel {
private jxl.Workbook rwb = null;
/**
* 得到當前工作薄的總列數
*
* @parma sheetIndex 工作薄號
* @return int
*/

public int getColCount(int sheetIndex) {

int colCnt = 0;
try {
jxl.Sheet rs = rwb.getSheet(sheetIndex);
colCnt = rs.getColumns();
} catch (Exception e) {
colCnt = 0;
} finally {
try {

} catch (Exception e) {
colCnt = 0;
}

}
return colCnt;

}

/**
* 得到當前工作薄的總行數
*
* @parma sheetIndex 工作薄號
* @return int
*/

public int getRowCount(int sheetIndex) {

int colCnt = 0;
try {
jxl.Sheet rs = rwb.getSheet(sheetIndex);
colCnt = rs.getRows();
} catch (Exception e) {
colCnt = 0;
} finally {
try {

} catch (Exception e) {
colCnt = 0;
}

}
return colCnt;

}
/**
* 打開Excel.
*
* @parma fileName Excel文件名+文件路徑(絕對路徑)
* @return boolean
*/
public boolean openExcel(String fileName) {
boolean Rtn = false;
try {
is = new FileInputStream(fileName);
rwb = Workbook.getWorkbook(is);
Rtn = true;
} catch (Exception e) {
Rtn = false;
} finally {
try {} catch (Exception e) {}
}
return Rtn;
}
/**
* 取得某個單元格的內容。不論單元格是何種數據類型都將返回字元型。
*
* @parma int col 列號 int row 行號
* @return String
*/
public String getCellContent(int col, int row) {
String cellContent = "";
try {
// 默認打開第一張工作薄。
Sheet rs = rwb.getSheet(0);
// 取得某一單元格的內容
Cell c00 = rs.getCell(col, row);
cellContent = c00.getContents();
} catch (Exception e) {
cellContent = "";
} finally {
try {

} catch (Exception e) {
cellContent = "";
}
}
return cellContent;
}
public static void main(String[] args) {
Excel ex = new Excel();
ex.openExcel("你自己的*.xls");

for (int i = 1; i < ex.getRowCount(0); i++) {
for (int j = 0; j < ex.getColCount(0); j++) {
System.out.println(ex.getCellContent(j, i));
}
}
}
}

7. java中excel表格導入實例

需要導入jxl.jar (在網上可以下載,然後放到lib文件夾中)
開放分類: java

通過java操作excel表格的工具類庫
支持Excel 95-2000的所有版本
生成Excel 2000標准格式
支持字體、數字、日期操作
能夠修飾單元格屬性
支持圖像和圖表
應該說以上功能已經能夠大致滿足我們的需要。最關鍵的是這套API是純Java的,並不依賴Windows系統,即使運行在Linux下,它同樣能夠正確的處理Excel文件。另外需要說明的是,這套API對圖形和圖表的支持很有限,而且僅僅識別PNG格式。
搭建環境
將下載後的文件解包,得到jxl.jar,放入classpath,安裝就完成了。

基本操作
一、創建文件
擬生成一個名為「測試數據.xls」的Excel文件,其中第一個工作表被命名為「第一頁」,大致效果如下:
代碼(CreateXLS.java):
//生成Excel的類
import java.io.*;
import jxl.*;
import jxl.write.*;
public class CreateXLS
{
public static void main(String args[])
{
try
{
//打開文件
WritableWorkbook book=
Workbook.createWorkbook(new File(「測試.xls」));
//生成名為「第一頁」的工作表,參數0表示這是第一頁
WritableSheet sheet=book.createSheet(「第一頁」,0);
//在Label對象的構造子中指名單元格位置是第一列第一行(0,0)
//以及單元格內容為test
Label label=new Label(0,0,」test」);
//將定義好的單元格添加到工作表中
sheet.addCell(label);
/*生成一個保存數字的單元格
必須使用Number的完整包路徑,否則有語法歧義
單元格位置是第二列,第一行,值為789.123*/
jxl.write.Number number = new jxl.write.Number(1,0,789.123);
sheet.addCell(number);
//寫入數據並關閉文件
book.write();
book.close();
}catch(Exception e)
{
System.out.println(e);
}
}
}
編譯執行後,會在當前位置產生一個Excel文件。

二、讀取文件
以剛才我們創建的Excel文件為例,做一個簡單的讀取操作,程序代碼如下:
//讀取Excel的類
import java.io.*;
import jxl.*;
public class ReadXLS
{
public static void main(String args[])
{
try
{
Workbook book=
Workbook.getWorkbook(new File(「測試.xls」));
//獲得第一個工作表對象
Sheet sheet=book.getSheet(0);
//得到第一列第一行的單元格
Cell cell1=sheet.getCell(0,0);
String result=cell1.getContents();
System.out.println(result);
book.close();
}catch(Exception e)
{
System.out.println(e);
}
}
}
程序執行結果:test
四、修改文件
利用jExcelAPI可以修改已有的Excel文件,修改Excel文件的時候,除了打開文件的方式不同之外,其他操作和創建Excel是一樣的。下面的例子是在我們已經生成的Excel文件中添加一個工作表:
//修改Excel的類,添加一個工作表
import java.io.*;
import jxl.*;
import jxl.write.*;
public class UpdateXLS
{
public static void main(String args[])
{
try
{
//Excel獲得文件
Workbook wb=Workbook.getWorkbook(new File(「測試.xls」));
//打開一個文件的副本,並且指定數據寫回到原文件
WritableWorkbook book=
Workbook.createWorkbook(new File(「測試.xls」),wb);
//添加一個工作表
WritableSheet sheet=book.createSheet(「第二頁」,1);
sheet.addCell(new Label(0,0,」第二頁的測試數據」));
book.write();
book.close();
}catch(Exception e)
{
System.out.println(e);
}
}
}

三、高級操作

數據格式化
在Excel中不涉及復雜的數據類型,能夠比較好的處理字串、數字和日期已經能夠滿足一般的應用。
1、 字串格式化
字元串的格式化涉及到的是字體、粗細、字型大小等元素,這些功能主要由WritableFont和WritableCellFormat類來負責。假設我們在生成一個含有字串的單元格時,使用如下語句,為方便敘述,我們為每一行命令加了編號:
WritableFont font1=
new WritableFont(WritableFont.TIMES,16,WritableFont.BOLD); 或//設置字體格式為excel支持的格式 WritableFont font3=new WritableFont(WritableFont.createFont("楷體_GB2312"),12,WritableFont.NO_BOLD );① WritableCellFormat format1=new WritableCellFormat(font1); ② Label label=new Label(0,0,」data 4 test」,format1) ③ 其中①指定了字串格式:字體為TIMES,字型大小16,加粗顯示。WritableFont有非常豐富的構造子,供不同情況下使用,jExcelAPI的java-doc中有詳細列表,這里不再列出。 ②處代碼使用了WritableCellFormat類,這個類非常重要,通過它可以指定單元格的各種屬性,後面的單元格格式化中會有更多描述。 ③處使用了Label類的構造子,指定了字串被賦予那種格式。 在WritableCellFormat類中,還有一個很重要的方法是指定數據的對齊方式,比如針對我們上面的實例,可以指定:
//把水平對齊方式指定為居中
format1.setAlignment(jxl.format.Alignment.CENTRE);
//把垂直對齊方式指定為居中
format1.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
//設置自動換行
format1.setWrap(true);

單元格操作
Excel中很重要的一部分是對單元格的操作,比如行高、列寬、單元格合並等,所幸jExcelAPI提供了這些支持。這些操作相對比較簡單,下面只介紹一下相關的API。
1、 合並單元格
WritableSheet.mergeCells(int m,int n,int p,int q);
作用是從(m,n)到(p,q)的單元格全部合並,比如:
WritableSheet sheet=book.createSheet(「第一頁」,0);
//合並第一列第一行到第六列第一行的所有單元格
sheet.mergeCells(0,0,5,0);
合並既可以是橫向的,也可以是縱向的。合並後的單元格不能再次進行合並,否則會觸發異常。
2、 行高和列寬
WritableSheet.setRowView(int i,int height);
作用是指定第i+1行的高度,比如:
//將第一行的高度設為200
sheet.setRowView(0,200);
WritableSheet.setColumnView(int i,int width);
作用是指定第i+1列的寬度,比如:
//將第一列的寬度設為30
sheet.setColumnView(0,30);

四、操作圖片
public static void write()throws Exception{
WritableWorkbook wwb=Workbook.createWorkbook(new File("c:/1.xls"));
WritableSheet ws=wwb.createSheet("Test Sheet 1",0);
File file=new File("C:\\jbproject\\PVS\\WebRoot\\weekhit\\1109496996281.png");
WritableImage image=new WritableImage(1, 4, 6, 18,file);
ws.addImage(image);
wwb.write();
wwb.close();
}
很簡單和插入單元格的方式一樣,不過就是參數多了些,WritableImage這個類繼承了Draw,上面只是他構造方法的一種,最後一個參數不用了說了,前面四個參數的類型都是double,依次是 x, y, width, height,注意,這里的寬和高可不是圖片的寬和高,而是圖片所要佔的單位格的個數,因為繼承的Draw所以他的類型必須是double,具體裡面怎麼實現的我還沒細看:)因為著急趕活,先完成功能,其他的以後有時間慢慢研究。以後會繼續寫出在使用中的心得給大家。
讀:
讀的時候是這樣的一個思路,先用一個輸入流(InputStream)得到Excel文件,然後用jxl中的Workbook得到工作薄,用Sheet從工作薄中得到工作表,用Cell得到工作表中得某個單元格.
InputStream->Workbook->Sheet->Cell,就得到了excel文件中的單元格
代碼:
String path="c:\\excel.xls";//Excel文件URL
InputStream is = new FileInputStream(path);//寫入到FileInputStream
jxl.Workbook wb = Workbook.getWorkbook(is); //得到工作薄
jxl.Sheet st = wb.getSheet(0);//得到工作薄中的第一個工作表
Cell cell=st.getCell(0,0);//得到工作表的第一個單元格,即A1
String content=cell.getContents();//getContents()將Cell中的字元轉為字元串
wb.close();//關閉工作薄
is.close();//關閉輸入流
我們可以通過Sheet的getCell(x,y)方法得到任意一個單元格,x,y和excel中的坐標對應.
例如A1對應(0,0),A2對應(0,1),D3對應(3,2).Excel中坐標從A,1開始,jxl中全部是從0開始.
還可以通過Sheet的getRows(),getColumns()方法得到行數列數,並用於循環控制,輸出一個sheet中的所有內容.
寫:
往Excel中寫入內容主要是用jxl.write包中的類.
思路是這樣的:
OutputStream<-WritableWorkbook<-WritableSheet<-Label
這裡面Label代表的是寫入Sheet的Cell位置及內容.
代碼:
OutputStream os=new FileOutputStream("c:\\test.xls");//輸出的Excel文件URL
WritableWorkbook wwb = Workbook.createWorkbook(os);//創建可寫工作薄
WritableSheet ws = wwb.createSheet("sheet1", 0);//創建可寫工作表
Label labelCF=new Label(0, 0, "hello");//創建寫入位置和內容
ws.addCell(labelCF);//將Label寫入sheet中
Label的構造函數Label(int x, int y,String aString)xy意同讀的時候的xy,aString是寫入的內容.
WritableFont wf = new WritableFont(WritableFont.TIMES, 12, WritableFont.BOLD, false);//設置寫入字體
WritableCellFormat wcfF = new WritableCellFormat(wf);//設置CellFormat
Label labelCF=new Label(0, 0, "hello");//創建寫入位置,內容和格式
Label的另一構造函數Label(int c, int r, String cont, CellFormat st)可以對寫入內容進行格式化,設置字體及其它的屬性.
現在可以寫了
wwb.write();
寫完後關閉
wwb.close();
輸出流也關閉吧
os.close;
OK,只要把讀和寫結合起來,就可以在N個Excel中讀取數據寫入你希望的Excel新表中,還是比較方便的.
下面是程序一例:
程序代碼:sql = "select * from tablename";
rs = stmt.executeQuery(sql);
//新建Excel文件
String filePath=request.getRealPath("aaa.xls");
File myFilePath=new File(filePath);
if(!myFilePath.exists())
myFilePath.createNewFile();
FileWriter resultFile=new FileWriter(myFilePath);
PrintWriter myFile=new PrintWriter(resultFile);
resultFile.close();
//用JXL向新建的文件中添加內容
OutputStream outf = new FileOutputStream(filePath);
jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(outf);
jxl.write.WritableSheet ws = wwb.createSheet("sheettest", 0);
int i=0;
int j=0;
for (int k = 0; k < rs.getMetaData().getColumnCount(); k++) {
ws.addCell(new Label(k,0,rs.getMetaData().getColumnName(k+1)));
}
while(rs.next()){
out.println(rs.getMetaData().getColumnCount());
for (int k = 0; k < rs.getMetaData().getColumnCount(); k++) {
ws.addCell(new Label(k,j+i+1,rs.getString(k+1)));
}
i++;
}
wwb.write();
wwb.close();
}catch(Exception e)
finally{
rs.close();
conn.close();
}
response.sendRedirect("aaa.xls");

8. java端導出Excel表格。

可以使用poi來實現導出execl表格或者通過io流實現導出execl表格,但是poi相對來說更方便
實例如下:
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();
}

}

熱點內容
資料庫的劃分的 發布:2025-07-02 00:43:19 瀏覽:654
補碼源碼和 發布:2025-07-02 00:37:25 瀏覽:978
centos7mysql遠程訪問 發布:2025-07-02 00:35:58 瀏覽:711
有線認證伺服器地址錯誤 發布:2025-07-02 00:33:22 瀏覽:278
本田思域2021款買哪個配置 發布:2025-07-02 00:31:43 瀏覽:326
安卓十二系統什麼時候更新 發布:2025-07-02 00:12:28 瀏覽:346
shell腳本需要編譯鏈接 發布:2025-07-02 00:04:20 瀏覽:475
微信如何重設密碼 發布:2025-07-02 00:02:27 瀏覽:546
java代碼基礎 發布:2025-07-02 00:00:46 瀏覽:305
煙花的代碼c語言 發布:2025-07-01 23:56:04 瀏覽:225