您的位置:首页 > 编程语言 > Java开发

java操作Excel的一种方法

2007-06-05 09:44 183 查看
搭建环境
将下载后的文件解包,得到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); ①

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);

二、单元格操作

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);

jExcelAPI还有其他的一些功能,比如插入图片等,这里就不再一一介绍,读者可以自己探索。

下面是我的代码
/*
* Created on 2005-6-27
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.eapt.uc.ftc.action.printnew;

import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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;
import org.apache.poi.hssf.util.Region;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.eapt.base.EAPTBaseAction;
import com.eapt.constants.FtcontractConstants;
import com.eapt.query.FtcontractheaderQuery;
import com.eapt.vo.EaptCustomer;
import com.eapt.vo.EaptFtcontractheader;
import com.eapt.vo.EaptFtcontractline;
import com.stony.core.exception.RunException;
import com.stony.core.util.CoreUtils;
import com.stony.core.util.ExcelStyle;

/**
* @author hardy.wu
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
*/
public class PrintEXPFtcontractExcelAction extends EAPTBaseAction {

protected ActionForward doWork(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {

String ftcontractno = request.getParameter("ftcontractno");

EaptFtcontractheader ftcontract = FtcontractheaderQuery
.loadByNoAllLine(new Long(ftcontractno));

setIsStream(response);

response.reset();

response.setContentType("application/vnd.ms-excel");

response.setHeader("Content-disposition", "attachment; filename="
+ ftcontract.getFtcontractcode() + ".xls");

OutputStream outputStream = response.getOutputStream();

exportExcel(request, outputStream, ftcontract);

return null;

}

public void exportExcel(HttpServletRequest request,
OutputStream outputStream, EaptFtcontractheader ftcontract) {

EaptCustomer buyer = EaptCustomer.getConstants(ftcontract.getBuyer()
.getCustomerno());

EaptCustomer seller = EaptCustomer.getConstants(ftcontract.getSeller()
.getCustomerno());

boolean ishk = false;

POIFSFileSystem fis;

HSSFWorkbook book;

HSSFSheet sheet;

HSSFRow row;

HSSFCell cell;

try {

fis = new POIFSFileSystem(new FileInputStream("c:/p2/expsale.xls"));

book = new HSSFWorkbook(fis);

book.setSheetName(0, "sheet1");

sheet = book.getSheetAt(0);

// 单元风格
HSSFCellStyle style1 = ExcelStyle
.getExpContractExportCellStyle1(book);

HSSFCellStyle style2 = ExcelStyle
.getExpContractExportCellStyle2(book);

HSSFCellStyle style3 = ExcelStyle
.getExpContractExportCellStyle3(book);

HSSFCellStyle style4 = ExcelStyle
.getExpContractExportCellStyle4(book);

HSSFCellStyle style6 = ExcelStyle
.getExpContractExportCellStyle6(book);

HSSFCellStyle style7 = ExcelStyle
.getExpContractExportCellStyle7(book);

HSSFCellStyle style8 = ExcelStyle
.getExpContractExportCellStyle8(book);

HSSFCellStyle style9 = ExcelStyle
.getExpContractExportCellStyle9(book);

HSSFCellStyle style10 = ExcelStyle
.getExpContractExportCellStyle10(book);

HSSFCellStyle style11 = ExcelStyle
.getExpContractExportCellStyle11(book);

HSSFCellStyle style12 = ExcelStyle
.getExpContractExportCellStyle12(book);

// 画表头
row = sheet.getRow(0);

cell = row.createCell((short) 0);
cell.setCellStyle(style6);
CoreUtils.setCellValue(cell, ishk, seller.getCustomernamecn());

row = sheet.getRow(1);

cell = row.createCell((short) 0);
cell.setCellStyle(style7);
CoreUtils.setCellValue(cell, ishk, seller.getCustomernameen());

row = sheet.getRow(2);

cell = row.createCell((short) 15);
cell.setCellStyle(style1);
CoreUtils
.setCellValue(cell, ishk,
FtcontractConstants.FTCNO_CUSTOMER
.equals(ftcontract.getFtcontractheader2()
.getCustomnotype()) ? ftcontract
.getFtcontractcode2() : ftcontract
.getFtcontractcode());

row = sheet.getRow(4);

Calendar calendar = Calendar.getInstance();
calendar.setTime(ftcontract.getCustomdate());
calendar.add(Calendar.DATE, -5);

cell = row.createCell((short) 15);
cell.setCellStyle(style1);
CoreUtils.setCellValue(cell, ishk, CoreUtils.formatDate(calendar
.getTime()));

row = sheet.getRow(5);

cell = row.createCell((short) 1);
cell.setCellStyle(style1);
CoreUtils.setCellValue(cell, ishk, seller.getFaxphone());

row = sheet.getRow(6);

cell = row.createCell((short) 16);
cell.setCellStyle(style2);
CoreUtils.setCellValue(cell, ishk, ftcontract
.getFtcontractheader2().getShipport());

row = sheet.getRow(7);

cell = row.createCell((short) 1);
cell.setCellStyle(style1);
CoreUtils.setCellValue(cell, ishk, seller.getTelephone());

row = sheet.getRow(9);

cell = row.createCell((short) 2);
cell.setCellStyle(style1);
CoreUtils.setCellValue(cell, ishk, seller.getAddress());

cell = row.createCell((short) 13);
cell.setCellStyle(style4);
CoreUtils.setCellValue(cell, ishk, buyer.getCustomernamecn()
+ "/r/n" + buyer.getCustomernameen());

row = sheet.getRow(11);

cell = row.createCell((short) 13);
cell.setCellStyle(style1);
CoreUtils.setCellValue(cell, ishk, buyer.getFaxphone());

row = sheet.getRow(13);

cell = row.createCell((short) 13);
cell.setCellStyle(style1);
CoreUtils.setCellValue(cell, ishk, buyer.getAddress());

row = sheet.getRow(17);

cell = row.createCell((short) 13);
cell.setCellStyle(style11);
CoreUtils.setCellValue(cell, ishk,
"单 价 Unit Price("
+ ftcontract.getFtccurrency() + ")");

cell = row.createCell((short) 18);
cell.setCellStyle(style12);
CoreUtils.setCellValue(cell, ishk,
"总 金 额 Total Amount("
+ ftcontract.getFtccurrency() + ")");

// 循环列出数据

int i = 0;

for (Iterator it = ftcontract.getEaptFtcontractlines().iterator(); it
.hasNext();) {

EaptFtcontractline ftcontractline = (EaptFtcontractline) it
.next();

row = sheet.createRow(18 + i);

row.setHeightInPoints(40);

cell = row.createCell((short) 0);
if (i == 0)
cell.setCellStyle(style8);
else
cell.setCellStyle(style3);
CoreUtils.setCellValue(cell, ishk, ftcontractline
.getCustomname());

cell = row.createCell((short) 9);
if (i == 0)
cell.setCellStyle(style9);
else
cell.setCellStyle(style10);
CoreUtils.setCellValue(cell, ishk, ftcontractline.getFtcqty());

cell = row.createCell((short) 13);
if (i == 0)
cell.setCellStyle(style9);
else
cell.setCellStyle(style10);
CoreUtils
.setCellValue(cell, ishk, ftcontractline.getFtcprice());

cell = row.createCell((short) 18);
if (i == 0)
cell.setCellStyle(style9);
else
cell.setCellStyle(style10);
CoreUtils.setCellValue(cell, ishk, ftcontractline.getAmount());

sheet.addMergedRegion(new Region(18 + i, (short) 0, 18 + i,
(short) 8));
sheet.addMergedRegion(new Region(18 + i, (short) 9, 18 + i,
(short) 12));

sheet.addMergedRegion(new Region(18 + i, (short) 13, 18 + i,
(short) 16));

sheet.addMergedRegion(new Region(18 + i, (short) 18, 18 + i,
(short) 19));

i++;

}

// 画Bottom

// 总价,允许溢短装
row = sheet.createRow(18 + i);

row.setHeightInPoints(20);

for (int j = 0; j < 20; j++) {
cell = row.createCell((short) j);
cell.setCellStyle(style4);
}

sheet.addMergedRegion(new Region(18 + i, (short) 0, 18 + i,
(short) 2));
sheet.addMergedRegion(new Region(18 + i, (short) 3, 18 + i,
(short) 8));
sheet.addMergedRegion(new Region(18 + i, (short) 9, 18 + i,
(short) 15));

cell = row.createCell((short) 0);
cell.setCellStyle(style4);
CoreUtils.setCellValue(cell, ishk, "总价/r/nTotal Value");

cell = row.createCell((short) 3);
cell.setCellStyle(style4);
CoreUtils.setCellValue(cell, ishk, ftcontract.getFtccurrency()
+ " " + ftcontract.getTotalftcamount() + " "
+ ftcontract.getTradeterm());

cell = row.createCell((short) 9);
cell.setCellStyle(style4);
CoreUtils.setCellValue(cell, ishk, "(允许溢短装Quantity Allowance ±");

cell = row.createCell((short) 16);
cell.setCellStyle(style4);
CoreUtils.setCellValue(cell, ishk, CoreUtils
.formatString(ftcontract.getCategory1()));

cell = row.createCell((short) 18);
cell.setCellStyle(style4);
CoreUtils.setCellValue(cell, ishk, "%)");

// 装运期
row = sheet.createRow(19 + i);
row.setHeightInPoints(10);

row = sheet.createRow(20 + i);
sheet.createRow(21 + i);

sheet.addMergedRegion(new Region(20 + i, (short) 3, 21 + i,
(short) 9));
sheet.addMergedRegion(new Region(20 + i, (short) 12, 21 + i,
(short) 15));
sheet.addMergedRegion(new Region(20 + i, (short) 17, 21 + i,
(short) 18));
sheet.addMergedRegion(new Region(20 + i, (short) 10, 20 + i,
(short) 11));

cell = row.createCell((short) 0);
cell.setCellStyle(style3);
CoreUtils.setCellValue(cell, ishk, "装运期:");

cell = row.createCell((short) 3);
cell.setCellStyle(style1);
CoreUtils.setCellValue(cell, ishk, "Before "
+ CoreUtils.formatDate(ftcontract.getFtcontractheader2()
.getShipdate()));

cell = row.createCell((short) 10);
cell.setCellStyle(style1);
CoreUtils.setCellValue(cell, ishk, "从:");

cell = row.createCell((short) 12);
cell.setCellStyle(style1);
CoreUtils.setCellValue(cell, ishk, CoreUtils
.formatString(ftcontract.getFtcontractheader2()
.getShipport()));

cell = row.createCell((short) 16);
cell.setCellStyle(style1);
CoreUtils.setCellValue(cell, ishk, "到:");

cell = row.createCell((short) 17);
cell.setCellStyle(style1);
CoreUtils.setCellValue(cell, ishk, CoreUtils
.formatString(ftcontract.getFtcontractheader2()
.getTargeport()));

// 21行
row = sheet.getRow(21 + i);

sheet.addMergedRegion(new Region(21 + i, (short) 10, 21 + i,
(short) 11));

cell = row.createCell((short) 0);
cell.setCellStyle(style1);
CoreUtils.setCellValue(cell, ishk, "Shipment:");

cell = row.createCell((short) 10);
cell.setCellStyle(style3);
CoreUtils.setCellValue(cell, ishk, "From:");

cell = row.createCell((short) 16);
cell.setCellStyle(style3);
CoreUtils.setCellValue(cell, ishk, "To:");

// draw bottom

String[] bottomtitles = getBottomTitle();
String[] bottomdatas = getBottomData(ftcontract);
float[] bottomheights = getBottomHeight();

int rn1 = 22 + i;
for (int j = 0; j < bottomtitles.length; j++) {

row = sheet.createRow(rn1 + j);

row.setHeightInPoints(bottomheights[j]);

sheet.addMergedRegion(new Region(rn1 + j, (short) 0, rn1 + j,
(short) 2));
sheet.addMergedRegion(new Region(rn1 + j, (short) 3, rn1 + j,
(short) 19));

cell = row.createCell((short) 0);
cell.setCellStyle(style3);
CoreUtils.setCellValue(cell, ishk, bottomtitles[j]);

cell = row.createCell((short) 3);
cell.setCellStyle(style3);
CoreUtils.setCellValue(cell, ishk, bottomdatas[j]);

}

int rn2 = 39 + i;
row = sheet.createRow(rn2 + 1);
row.setHeightInPoints(10);
row = sheet.createRow(rn2 + 2);
row.setHeightInPoints(10);

row = sheet.createRow(rn2 + 3);

sheet.addMergedRegion(new Region(rn2 + 3, (short) 3, rn2 + 3,
(short) 4));
sheet.addMergedRegion(new Region(rn2 + 3, (short) 10, rn2 + 3,
(short) 14));

cell = row.createCell((short) 3);
cell.setCellStyle(style1);
CoreUtils.setCellValue(cell, ishk, "买方");

cell = row.createCell((short) 10);
cell.setCellStyle(style1);
CoreUtils.setCellValue(cell, ishk, "卖方");

row = sheet.createRow(rn2 + 4);

sheet.addMergedRegion(new Region(rn2 + 4, (short) 3, rn2 + 4,
(short) 4));
sheet.addMergedRegion(new Region(rn2 + 4, (short) 10, rn2 + 4,
(short) 14));

cell = row.createCell((short) 3);
cell.setCellStyle(style1);
CoreUtils.setCellValue(cell, ishk, "(The Buyers)");

cell = row.createCell((short) 10);
cell.setCellStyle(style1);
CoreUtils.setCellValue(cell, ishk, "(The Sellers)");

book.write(outputStream);

} catch (Exception ex) {

ex.printStackTrace();

throw new RunException("error.excel.download");

}

}

public String[] getBottomTitle() {

String[] bottomtitles = new String[18];

bottomtitles[0] = "付款方式:";
bottomtitles[1] = "Payment:";
bottomtitles[2] = "检 验:";
bottomtitles[3] = "Inspection:";
bottomtitles[4] = "保 险:";
bottomtitles[5] = "Insurance:";
bottomtitles[6] = "仲 裁:";
bottomtitles[7] = "Arbitration:";
bottomtitles[8] = "一般条款:";
bottomtitles[9] = "Ceneral Terms:";
bottomtitles[10] = "";
bottomtitles[11] = "";
bottomtitles[12] = "";
bottomtitles[13] = "";
bottomtitles[14] = "";
bottomtitles[15] = "";
bottomtitles[16] = "";
bottomtitles[17] = "";

return bottomtitles;

}

public float[] getBottomHeight() {

float[] bottomheights = new float[18];

bottomheights[0] = 10;
bottomheights[1] = 30;
bottomheights[2] = 10;
bottomheights[3] = 20;
bottomheights[4] = 10;
bottomheights[5] = 20;
bottomheights[6] = 20;
bottomheights[7] = 40;
bottomheights[8] = 10;
bottomheights[9] = 20;
bottomheights[10] = 20;
bottomheights[11] = 40;
bottomheights[12] = 10;
bottomheights[13] = 20;
bottomheights[14] = 10;
bottomheights[15] = 10;
bottomheights[16] = 25;
bottomheights[17] = 30;

return bottomheights;

}

public String[] getBottomData(EaptFtcontractheader ftcontract) {

String[] bottomdatas = new String[18];

bottomdatas[0] = "BY "
+ CoreUtils.formatString(ftcontract.getPaymentmark());
bottomdatas[1] = "口By 100% confirmed&irrevocable L/C to be available by days sight,reaching the sellers before the date of shipment,remaining valid for in China for further 15 days after the prescribed time of shpment,allowing transhipment&Partial Shipments. ";
bottomdatas[2] = "品质、数量、重量以中华人民共和国进出口商品检验局的检验证或卖方所出之证明书为最后依据。";
bottomdatas[3] = "Quality,quantity and weight certified by Import & Export Commodity Inspection Bureau of the P.R.of China or the Sellers. As per the former`s Inspection Certificate of the latter`s certificate,are to be taken as final.";
bottomdatas[4] = "";
bottomdatas[5] = "口To be effected by the buyers. 口To be effected by the sellers at 110% of invoice value covering as per China Insuranec Clauses (C.I.C.)";
bottomdatas[6] = "凡因执行本合同所发生的或与本合同有关的一切争议,应由双方通过友好协商解决;如果协商不能解决,应提交中国国际经济贸易仲裁委员会根据该会的仲裁规则进行仲裁,仲裁地点在北京,仲裁裁决是终局的对双方都有约束力";
bottomdatas[7] = "口All disputes arising from the execution of,or in connection with this contract, shall be settled amicably through friendly negotiation.`Incase no settlement can be reached through negotiation,the case shall then be submitted to the China International Economic and Trade Arbitration Commission,Beijing,for arbitration in accordance with its rules of procedure.The arbitral award is final and is final and binding upon both paries.";
bottomdatas[8] = "1.质地、重量、尺寸、花型、颜色均允许合理差异。对合理范围内差异提出的索赔,概不受理。";
bottomdatas[9] = "Reasonable tolerance in quality,weight,measurements,designs and colours is allowed,for which no claims will be entertained.";
bottomdatas[10] = "2.买方对下列各点所造成的后果承担全部责任: (甲)买方要求卖方使用买方的特定装潢,花型图案商票等;(乙)不及时提供生产所需的规格或其他细则;(丙)不按时开信用证;(丁)信用证条款与售货合同不相符而不及时修改。";
bottomdatas[11] = "Buyers are to assume full responsibilities for any consequences arising from:(a)the use of packing,designs or brand pattern made to order;(b)late submission of specifications of any details necessary for the execution of this Sales Contract;(c)late establishment of L/C:(d)late amendment to L/C inconsistent with the provisions of this Sales Contract.";
bottomdatas[12] = "3.人力不可抗拒的事故造成延期或无法交货者,卖方不负任何责任。";
bottomdatas[13] = "Sellers are not responsible for late or non-delivery in the event of force majeure of any contingences beyond sellers control.";
bottomdatas[14] = "4.凡有对装达的货物质量提出索赔者,必须在货到目的港后30天内提出。";
bottomdatas[15] = "Claims,if any,concerning the goods shipped should be filed within 30 days after arrival at destination.";
bottomdatas[16] = "5.买方应在收到本售货合同后十天内签退一份给卖方。如在此期限内不提任何异议,本售货合同即生效。凭买方定单或买方先前之确认而缮制的售货合同发出后即生效。非经双方同意,不得更改或撤销。";
bottomdatas[17] = "Buyers should sign one copoy of this Sales contract and return it to sellers within 10 bays after receipt,If nothing is proposed to the contrary within that time,this Sales Contract will be to neither modification nor cancellation,unless agreed upon by both parties.";

return bottomdatas;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: