Java中Excel参数怎么写?XSSFWorkbook wb=new XSSFWorkbook(参数);中的参数是InputStream ,你直接XSSFWorkbook wb=new XSSFWorkbook(fs);就可以了。那么,Java中Excel参数怎么写?一起来了解一下吧。
XSSFWorkbook wb=new XSSFWorkbook(参数);中的参数是InputStream ,你直接XSSFWorkbook wb=new XSSFWorkbook(fs);就可以了。
第一步查询数据--这一步读者自行实现自己的数据御磨判查询List
points = this.dao.getAllCollect(userId);
final Map
for (final PointInfo pointInfo : points) {
final String pt = pointInfo.getPointType();if (pointMap.containsKey(pt)) {final List
subList.add(pointInfo);
} else {final List
pointMap.put(pt, subList
第二步:生成工作簿
final SXSSFWorkbook wb = new SXSSFWorkbook();
// 对每一种类型生成一个sheet
for (final Map.Entry
final List
// 获取每种类型的名字--作为sheet显示名称--如果不需要分sheet可忽略
String typeName = "";
if (this.dao.getTypeByTypeCode(pts.get(0).getPointType()) != null) {
typeName = this.dao.getTypeByTypeCode(pts.get(0).getPointType()).getPointTypeName();
}
final Sheet sheet = wb.createSheet(typeName);
//生成用于插入图片的容器--这个方法返回的类型在老api中不同
final Drawing patriarch = sheet.createDrawingPatriarch();
// 为sheet1生成第一行,用于放表头信息
final Row row = sheet.createRow(0);
// 第一行的第一个单元格的值镇改游罩
Cell cell = row.createCell((short) 0);
cell.setCellValue("详细地址");
cell = row.createCell((short) 1);
cell.setCellValue("经度");
cell = row.createCell((short) 2);
cell.setCellValue("纬度");
cell = row.createCell((short) 3);
for (int i = 0; i < pts.size(); i++) {
final Row each = sheet.createRow(i + 1);
Cell infoCell = each.createCell((short) 0);
infoCell.setCellValue(pts.get(i).getAddrDetail());
infoCell = each.createCell((short) 1);
infoCell.setCellValue(pts.get(i).getX());
infoCell = each.createCell((short) 2);
infoCell.setCellValue(pts.get(i).getY());
infoCell = each.createCell((short) 3);
//查询获取图片路径信息--该步读者自定义
PointPic pic = this.dao.getPicInfoByPointId(pts.get(i).getId());
try {
if (pic != null) {
for (int k = 0; k < 6; k++) {//因为有六张图片,所以循环6次
final short colNum = (short) (4+k);
infoCell = each.createCell(colNum);
BufferedImage img = null;
switch (k) {
case 0:
if (!StringUtils.isEmpty(pic.getPicOneAddr())) {
File imgFile = new File(pic.getPicOneAddr());
img = ImageIO.read(imgFile);
imgFile = null;
}
break;
case 1:
if (!StringUtils.isEmpty(pic.getPicTwoAddr())) {
File imgFile = new File(pic.getPicTwoAddr());
img = ImageIO.read(imgFile);
imgFile = null;
}
break;
case 2:
if (!StringUtils.isEmpty(pic.getPicThreeAddr())) {
File imgFile = new File(pic.getPicThreeAddr());
img = ImageIO.read(imgFile);
imgFile = null;
}
break;
case 3:
if (!StringUtils.isEmpty(pic.getPicFourAddr())) {
File imgFile = new File(pic.getPicFourAddr());
img = ImageIO.read(imgFile);
imgFile = null;
}
break;
case 4:
if (!StringUtils.isEmpty(pic.getPicFiveAddr())) {
File imgFile = new File(pic.getPicFiveAddr());
img = ImageIO.read(imgFile);
imgFile = null;
}
break;
case 5:
if (!StringUtils.isEmpty(pic.getPicSixAddr())) {
File imgFile = new File(pic.getPicSixAddr());
img = ImageIO.read(imgFile);
imgFile = null;
}
break;
}
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", byteArrayOut);
img = null;
//设置每张图片插入位置
final XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, colNum,
i + 1, (short) (colNum + 1), i + 2);//参数为图片插入在表格的坐标,可以自行查看api研究参数
anchor.setAnchorType(0);
// 插入图片
patriarch.createPicture(anchor, wb.addPicture(
byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
byteArrayOut.close();
byteArrayOut = null;
}
pic = null;
}
} catch (final Exception e) {
e.printStackTrace();
}
}
}
final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
wb.write(os);
} catch (final IOException e) {
e.printStackTrace();
}
final byte[] content = os.toByteArray();
final String url = Var.BASE_URL+ File.separator + "output.xls";//读者自定义路径
final File file = new File(url);// 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为被copy对象,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);//copy
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();
}
}
}
public void export(List
// 准备设置excel工作表的标题
// 创建Excel工作薄
WritableWorkbook wwb = null;
try {
// 输出的excel的路径
String filePath1 = Const.pathStr+Const.pathStr4+Const.pathStr3;
File file = new File(filePath1);
if(!file.exists()){
file.mkdir();
}
String filePath=filePath1+Const.pathStr4+Const.pathStr6+dateString+Const.pathStr5;
// 新建立一个jxl文件,即在C盘下生成testJXL.xls
OutputStream os = new FileOutputStream(filePath);
wwb = Workbook.createWorkbook(os);
// 添加第一个工作表并设置渣姿陪第一个Sheet的名字
WritableSheet sheet = wwb.createSheet("设备清单", 0);
Label label;
for (int i = 0; i < title.length; i++) {
// Label(x,y,z) 代表单元格的第x+1列,第y+1行, 内容z
// 在Label对象的子对象中指明单元格的位置和内容
label = new Label(i, 0, title[i]);
//如蠢 将定义好的单元格添加到工作表中
sheet.addCell(label);
}
for (int i = 0; i < li.size(); i++) {
int j = 0;
j = i + 1;
//填充单元格
//获取区域名称
label = new Label(0, j, li.get(i).getQyName());
sheet.addCell(label);
//获取区域名称
label = new Label(1, j, li.get(i).getJzName());
sheet.addCell(label);
//获取设备名称
label = new Label(2, j, li.get(i).getLnodeName());
sheet.addCell(label);
////获取设备类型名称
label = new Label(3, j, li.get(i).getSbxh());
sheet.addCell(label);
//获取运行状态
label = new Label(4, j, li.get(i).getYxzh());
sheet.addCell(label);
//获取删除状态
label = new Label(5, j, li.get(i).getDeleteFlag());
sheet.addCell(label);
//获取启用状态
label = new Label(6, j, li.get(i).getQyzt());
sheet.addCell(label);
//获取设备投运日期
label = new Label(7, j, li.get(i).getSbtyri());
sheet.addCell(label);
//获取使册唯用年限
jxl.write.Number numb1 = new jxl.write.Number(8, j, li.get(i).getSynx());
sheet.addCell(numb1);
//获取区域名称
label = new Label(9, j, li.get(i).getAddUser());
sheet.addCell(label);
//获取区域名称
label = new Label(10, j, li.get(i).getUpdUser());
sheet.addCell(label);
//获取区域名称
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String newdate = sdf.format(li.get(i).getUpdTime());
label = new Label(11, j, newdate);
sheet.addCell(label);
//获取区域名称
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
String newdate2 = sdf2.format(li.get(i).getAddTime());
label = new Label(12, j, newdate2);
sheet.addCell(label);
//获取区域名称
label = new Label(13, j, li.get(i).getZcbh());
sheet.addCell(label);
//获取区域名称
label = new Label(14, j, li.get(i).getSbcs());
sheet.addCell(label);
//获取区域名称
jxl.write.Number numb2 = new jxl.write.Number(15, j, li.get(i)
.getSbll());
sheet.addCell(numb2);
//获取区域名称
label = new Label(16, j, li.get(i).getRldw());
sheet.addCell(label);
//获取区域名称
label = new Label(17, j, li.get(i).getWxghjl());
sheet.addCell(label);
}
// 写入数据
wwb.write();
} catch (Exception e) {
e.printStackTrace();
}finally{
// 关闭文件
wwb.close();
}
}
Const文件:
/**路径:C盘*/
public static String pathStr = "C:";
/**路径://*/
public static String pathStr2 = "//";
/**文件夹:workspace*/
public static String pathStr3 = "exportFile";
/**文件名:world*/
public static String pathStr6 = "Equipment";
/**路径:/*/
public static String pathStr4 = "/";
/**路径:.xls*/
public static String pathStr5 = ".xls";
我猛扒们项目里用的 供你参考,没写全,你可以自己百度下
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableImage;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
/**
* 导出excel
* @param reportParams导出excel列名标示
* @param list导出excel值
* @param headersexcel头
* @param reportName·excel的sheet名
* @param response
* @param startRow从哪一行开始放list值
* @param startCol从哪一列开始放list值
* @return
*/
public boolean report(ReportBean rb, List list, XlsHeaderBean[] headers, String reportName, HttpServletResponse response, int startRow, int startCol, HttpServletRequest request){
WritableWorkbook wwb = null;
OutputStream os;
boolean flag = true;
Date date = new Date();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String strDate = format.format(date);
try {
// 用Workbook类的工厂方法创建工作薄(Workbook)对象
response.setContentType("application/x-msdownload");
String sheetName = "report";
sheetName = sheetName.replaceAll(":", "").replaceAll("[)]", "")
.replaceAll("[(]", "");
// 这里解释一下
// attachment; 这个代表要的,如果去掉就编程直接打开了
// filename是文件名,另存李知迟为或者时,为默认的文件名
response.addHeader("Content-Disposition", "attachment; filename="
+ new String(sheetName.getBytes("UTF-8"), "ISO-8859-1")+ strDate
+ "哪李.xls");
os = response.getOutputStream();
wwb = Workbook.createWorkbook(os);
} catch (IOException e) {
e.printStackTrace();
return flag = false;
}
if (wwb != null) {
// 创建一个可写入的工作表
// Workbook的createSheet方法两个参数,1名称,2位置
WritableSheet ws = wwb.createSheet(reportName, 0);
// 下面开始添加单元格
// 导出excel
try {
Label labelC = null;
for(int j = 0; j < headers.length; j++){
if(headers[j].isUnion()){
ws.mergeCells(headers[j].getCol(), headers[j].getRow(), headers[j].getCol()+headers[j].getColLength(), headers[j].getRow()+headers[j].getRowLength());
}
labelC = new Label(headers[j].getCol(), headers[j].getRow(), headers[j].getValue());
ws.addCell(labelC);
}
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
String value = null;
for (int i = 0; i < list.size(); i++) {
Map values = (Map)list.get(i);
for (int j = 0; j < rb.getReportParams().length; j++) {
// 这里需要注意的是,在Excel中,第一个参数表示列,第二个表示行
Label labelC;
if(values.get(rb.getReportParams()[j]) == null){
value = "";
} else {
if(values.get(rb.getReportParams()[j]) instanceof java.util.Date){
value = format.format(values.get(rb.getReportParams()[j]));
} else if(values.get(rb.getReportParams()[j]) instanceof java.math.BigDecimal){
value = values.get(rb.getReportParams()[j]).toString();
} else {
value = values.get(rb.getReportParams()[j]).toString();
}
}
labelC = new Label(j+startCol, i + startRow, value);
try {
// 将生成的单元格添加到工作表中
ws.addCell(labelC);
} catch (RowsExceededException e) {
e.printStackTrace();
return flag = false;
} catch (WriteException e) {
e.printStackTrace();
return flag = false;
}
}
}
if(rb.isHasImg()){
String rootPath = this.getServletContext().getRealPath("savefiles");
String imgPath = rb.getImgPath();
if(rootPath != null && rootPath.compareTo("") != 0 && imgPath != null && imgPath.compareTo("") !=0){
String[] strs = imgPath.split("\\/");
String imgName = strs[strs.length-1];
File file = new File(rootPath + File.separator + imgName);
if(file.exists()){
WritableImage wi = new WritableImage(0, startRow + list.size() + 2,12,20, file);
ws.addImage(wi);
}
}
}
try {
// 从内存中写入文件中
wwb.write();
wwb.close();
return flag;
} catch (IOException e) {
e.printStackTrace();
return flag = false;
} catch (WriteException e) {
e.printStackTrace();
return flag = false;
}
}
return flag;
}
给你个我以前写的小例子好了
怎么也得改改才好用,是用的jxl的库,你可以从网上一个jxl.jar导到你的项目里衡行
看看它的API有不少例子,好像是韩国人写的写点小东西还好有BUG,大项目的话用apache的POI
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
51
public class exportEXL {
String fileName= "F:\\NumberProcessed.xls";
String sheetName ="sheet";
private int location = 1;
public void ExportFile(int[] arr) throws WriteException, IOException{
WritableWorkbook wwb = null;
//字体设置,全部参数集中于format变量枯拦枯中
WritableFont wf = new WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD, false);
DisplayFormat displayFormat = NumberFormats.INTEGER;
WritableCellFormat format = new WritableCellFormat(wf,displayFormat);
format.setAlignment(jxl.format.Alignment.RIGHT);
format.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.NONE);
try {
// 创建可写入的工作簿对象
wwb = Workbook.createWorkbook(new File(fileName));
if (wwb != null) {
// 在工作簿里创建可写入的工作表,第一个参数为工作表名,第二个参数为该工作表的所在位置
WritableSheet ws = wwb.createSheet(sheetName, location);
if (ws != null) {
/* 添加表结构 */
for(int j =1;j<=93;j++){
for(int i=0;i { //number参数中第一个参数是列,从零开始 //第二个参数是行,没洞从零开始,此程序中每隔75行重复一次 jxl.write.Number number = new jxl.write.Number(0, i+(j-1)*arr.length, Integer.parseInt(Integer.toString(arr[i])),format); //写入单元格 ws.addCell(number); arr[i] = arr[i]+500; } } } } // 从内存中写入到文件 wwb.write(); System.out.println("路径为:" + fileName + "的工作簿写入数据成功!"); } catch (Exception e) { System.out.println(e.getMessage()); } finally { wwb.close(); } } } 以上就是Java中Excel参数怎么写的全部内容,Java Excel API提供了许多访问Excel数据表的方法,在这里我只简要地介绍几个常用的方法,其它的方法请参考附录中的Java Excel API Document。