Java 操作excel表格 - JXL(Java excel api)

Java 操作excel表格

Java 操作 Excel 最常用的就是JXL(Java excel api)和POI,用起来挺简单的,不过相应的其功能也并非很强大,够用就行!

首先,下载jxl.jar 文件,点我下载
其次,将jxl.jar导入项目

操作步骤:鼠标选中项目右击 =》 最后一项(Properties) => 选择第三项(Java Build Path) => 选择第三项(Libraries)=> 选择 Add JARs… => 找到下载好的 jsx.jar目录,导入即可!

示例图


一、创建工作簿:

WritableWorkbook workbook = Workbook.createWorkbook(new File("d:/AA/test.xls"));

// 创建新的一页
WritableSheet sheet = workbook.createSheet("First Sheet", 0);

二、简单功能及其方法介绍

接下来,介绍下WritableWorkbook所提供的方法(对应的excel的功能)

WritableSheet sheet = workbook.getSheet(0);  

1、修改sheet名字

sheet.setName(“第一页”); // 给sheet页改名

2、删除多余的sheet页面

workbook.removeSheet(2); // 移除多余的标签页

3、单元格合并

sheet.mergeCells(0, 0, 4, 0); // 合并单元格,第一个参数是起始列,第二个参数是起始行,第三个参数是终止列,第四个参数是终止行

4、设置行高,列宽

sheet.setRowView(0, 600); // 设置行的高度  
sheet.setColumnView(0, 30); // 设置列的宽度 

5、设置文字颜色、文字大小、粗细,下划线、斜体、文字垂直/水平居中及其内容溢出自动换行

WritableFont color = new WritableFont(WritableFont.createFont("仿宋_GB2312"),// 字体  
                            20,//WritableFont.DEFAULT_POINT_SIZE,   // 字号  
                            WritableFont.NO_BOLD,                  // 粗体  
                            false,                                 // 斜体  
                            UnderlineStyle.NO_UNDERLINE,            // 下划线  
                            Colour.BLUE2,                       // 字体颜色  
                            ScriptStyle.NORMAL_SCRIPT); 
color.setColour(Colour.BLACK);// 设置字体颜色为黑色
WritableCellFormat colorFormat = new WritableCellFormat(color);
colorFormat.setAlignment(jxl.format.Alignment.CENTRE);// 单元格中的内容水平方向居中
colorFormat.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);// 单元格的内容垂直方向居中
colorFormat.setBackground(Colour.GRAY_25);// 设置单元格的背景颜色  

colorFormat.setWrap(true);//自动换行

colorFormat.setAlignment(Alignment.RIGHT); //右对齐


6、把创建的内容写入到输出流中,并关闭输出流

workbook.write();
workbook.close();
os.close();

7、添加图片

  // 在B32处添加图片,图片大小占103列,只支持png格式  
 File file = new File("d:\\shu05.png");  
 WritableImage image = new WritableImage(1, 31, 3, 10, file);  
 sheet.addImage(image); 

8、添加一个下拉列表并添加注释

 Blank b = new Blank(1, 43);  
 wcfeatures = new WritableCellFeatures();  
 ArrayList al = new ArrayList();  
 al.add("why");  
 al.add("landor");  
 al.add("tjm");  
 wcfeatures.setDataValidationList(al);  
 wcfeatures.setComment("这是一个注释");  
 b.setCellFeatures(wcfeatures);  
 sheet.addCell(b);  

。。。还有很多


示例效果图

image

示例代码:

package com.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

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

import jxl.Workbook;
import jxl.format.Colour;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableImage;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import com.empty.Empty;

public class readOrWriteServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doPost(request, response);
    }

    @SuppressWarnings("static-access")
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");// 设置相应内容的编码格式
        request.setCharacterEncoding("UTF-8");

        String fname = "院士专家工作站人员动态服务表";
        fname = java.net.URLEncoder.encode(fname, "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename="
                + new String(fname.getBytes("UTF-8"), "GBK") + ".xls");

        PrintWriter out = response.getWriter();
        try {

            String _UserName = request.getParameter("_UserName");
            String _Sex = request.getParameter("_Sex");
            String _Birth = request.getParameter("_Birth");

            Empty emp = new Empty();
            emp._UserName = _UserName;
            emp._Sex = _Sex;
            emp._Birth = _Birth;

            String mokDir = "d:/CloudJingHai";// 文件夹
            this.createDir(mokDir);// 创建文件夹

            // 读取文件
            File file = new File(mokDir + "/" + _UserName + ".xls");
            if (file.exists()) {
                out.println("该文件已存在");
                return;
            }

            OutputStream os = new FileOutputStream(file);// 取得输出流
            this.createExcel(os, emp);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void createExcel(OutputStream os, Empty emp) throws WriteException,
            IOException {
        // 创建工作薄
        WritableWorkbook workbook = Workbook.createWorkbook(os);
        // 创建新的一页
        WritableSheet sheet = workbook.createSheet("First Sheet", 0);
        //设置列宽
        sheet.setColumnView(0,15);
        sheet.setColumnView(1,15);
        sheet.setColumnView(2,15);
        sheet.setColumnView(3,15);
        sheet.setColumnView(4,20);
        sheet.setColumnView(5,20);
        sheet.setColumnView(6,30);
        //行高
        sheet.setRowView(0, 1200, false);// 设置第一行的高度
        sheet.setRowView(1, 800, false);// 设置第一行的高度
        sheet.setRowView(2, 800, false);// 设置第一行的高度
        sheet.setRowView(3, 800, false);// 设置第一行的高度
        sheet.setRowView(4, 800, false);// 设置第一行的高度
        sheet.setRowView(5, 800, false);// 设置第一行的高度
        sheet.setRowView(6, 800, false);// 设置第一行的高度
        sheet.setRowView(7, 6000, false);// 设置第一行的高度
        // 构造表头
        sheet.mergeCells(0, 0, 6, 0);// 添加合并单元格,第一个参数是起始列,第二个参数是起始行,第三个参数是终止列,第四个参数是终止行
        WritableFont bold = new WritableFont(WritableFont.ARIAL, 14,
                WritableFont.BOLD);// 设置字体种类和黑体显示,字体为Arial,字号大小为14,采用黑体显示
        WritableCellFormat titleFormate = new WritableCellFormat(bold);// 生成一个单元格样式控制对象
        titleFormate.setAlignment(jxl.format.Alignment.CENTRE);// 单元格中的内容水平方向居中
        titleFormate.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);// 单元格的内容垂直方向居中
        Label title = new Label(0, 0, "院士专家工作站人员动态服务表", titleFormate);

        sheet.addCell(title);

        // 创建要显示的具体内容
        WritableFont color = new WritableFont(WritableFont.ARIAL,10,WritableFont.BOLD);// 选择字体
        color.setColour(Colour.BLACK);// 设置字体颜色为金黄色
        WritableCellFormat colorFormat = new WritableCellFormat(color);
        colorFormat.setAlignment(jxl.format.Alignment.CENTRE);// 单元格中的内容水平方向居中
        colorFormat.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);// 单元格的内容垂直方向居中
        colorFormat.setWrap(true);//自动换行

        WritableFont color1 = new WritableFont(WritableFont.ARIAL);// 选择字体
        color1.setColour(Colour.GREEN);// 设置字体颜色为金黄色
        WritableCellFormat colorFormat1 = new WritableCellFormat(color1);
        colorFormat1.setAlignment(jxl.format.Alignment.CENTRE);// 单元格中的内容水平方向居中
        colorFormat1.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);// 单元格的内容垂直方向居中
        colorFormat1.setWrap(true);//自动换行

        Label formate = new Label(0, 1, "姓      名",colorFormat);
        sheet.addCell(formate);
        Label username = new Label(1, 1, emp._UserName,colorFormat1);
        sheet.addCell(username);
        Label floats = new Label(2, 1, "性      别",colorFormat);
        sheet.addCell(floats);
        Label username1 = new Label(3, 1, emp._Sex,colorFormat1);
        sheet.addCell(username1);
        Label integers = new Label(4, 1, "出生年月",colorFormat);
        sheet.addCell(integers);
        Label Birth = new Label(5, 1, emp._Birth,colorFormat1);
        sheet.addCell(Birth);

        Label booleans = new Label(6, 1, "图      片",colorFormat);
        File file = new File("D:/CloudJingHai/AA.png"); //只支持png格式  
        WritableImage image = new WritableImage(6, 1, 1, 4, file);  
        sheet.addImage(image);  

        sheet.addCell(booleans);

        // 第二行
        Label example = new Label(0, 2, "籍      贯",colorFormat);
        sheet.addCell(example);
        Label jiguan = new Label(1, 2, "北京市海淀区",colorFormat1);
        sheet.mergeCells(1, 2, 2, 2);// 添加合并单元格,第一个参数是起始列,第二个参数是起始行,第三个参数是终止列,第四个参数是终止行
        sheet.addCell(jiguan);
        Label example2 = new Label(3, 2, "身份证号码",colorFormat);
        sheet.mergeCells(4, 2, 5, 2);
        sheet.addCell(example2);
        Label cardId = new Label(4, 2, "1545",colorFormat1);
        sheet.addCell(cardId);



        // 第三行
        Label _graduationSchool = new Label(0, 3, "毕业学校",colorFormat);
        sheet.addCell(_graduationSchool);
        Label SchoolName = new Label(1, 3, "北京大学",colorFormat1);
        sheet.addCell(SchoolName);
        Label _graduationTime = new Label(2, 3, "毕业时间",colorFormat);
        sheet.addCell(_graduationTime);
        Label _graduationTimeName = new Label(3, 3, "2015-05-05",colorFormat1);
        sheet.addCell(_graduationTimeName);
        Label _Culture = new Label(4, 3, "文化程度",colorFormat);
        sheet.addCell(_Culture);
        Label _CultureName = new Label(5, 3, "本科",colorFormat1);
        sheet.addCell(_CultureName);

        //第四行
        Label _Education = new Label(0, 4, "学      历",colorFormat);
        sheet.addCell(_Education);
        Label _EducationName = new Label(1, 4, "本科",colorFormat1);
        sheet.mergeCells(1, 4, 2, 4);//我的理解 第一个参数表示起始列,第二个参数表示第几行,第三个参数表示合并到第几格(结束为止),第四个参数表示结束行
        sheet.addCell(_EducationName);
        Label _major = new Label(3, 4, "所学专业",colorFormat);
        sheet.addCell(_major);
        Label _majorName = new Label(4, 4, "计算机",colorFormat1);
        sheet.mergeCells(4, 4, 5, 4);
        sheet.addCell(_majorName);

        //第五行
        Label _department = new Label(0, 5, "工作部门",colorFormat);
        sheet.addCell(_department);
        Label _departmentName = new Label(1, 5, "亚发布",colorFormat1);
        sheet.mergeCells(1, 5, 2, 5);//第一列,第五行,何必结束列,结束行
        sheet.addCell(_departmentName);
        Label _post = new Label(3, 5, "岗      位",colorFormat);
        sheet.addCell(_post);
        Label _postName = new Label(4, 5, "前端",colorFormat1);
        sheet.mergeCells(4, 5, 6, 5);
        sheet.addCell(_postName);


        //第六行
        Label _business = new Label(0, 6, "职      务",colorFormat);
        sheet.addCell(_business);
        Label _businessName = new Label(1, 6, "职务",colorFormat1);
        sheet.mergeCells(1, 6, 2, 6);//第一列,第五行,结束列,结束行
        sheet.addCell(_businessName);
        Label _Tenure = new Label(3, 6, "任职时间",colorFormat);
        sheet.addCell(_Tenure);
        Label _TenureName = new Label(4, 6, "2016-05-05",colorFormat1);
        sheet.mergeCells(4, 6, 6, 6);
        sheet.addCell(_TenureName);


        //第7行
        Label _introduction = new Label(0, 7, "个人情况简介",colorFormat);
        sheet.addCell(_introduction);
        Label _introductionName = new Label(1, 7, "我是一个兵来自老板姓,我是一个兵来自老板姓,我是一个兵来自老板姓",colorFormat1);
        sheet.mergeCells(1, 7, 6, 7);
        sheet.addCell(_introductionName);






        // 把创建的内容写入到输出流中,并关闭输出流
        workbook.write();
        workbook.close();
        os.close();

    }

    // 创建目录
    public static boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {// 判断目录是否存在
            System.out.println("创建目录失败,目标目录已存在!");
            return false;
        }
        if (!destDirName.endsWith(File.separator)) {// 结尾是否以"/"结束
            destDirName = destDirName + File.separator;
        }
        if (dir.mkdirs()) {// 创建目标目录
            System.out.println("创建目录成功!" + destDirName);
            return true;
        } else {
            System.out.println("创建目录失败!");
            return false;
        }
    }

}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rkatsiteli

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值