一,操作Excel表格:
首先 我们需要去下载它的jar包:
点击下载
下载好了之后 我们就导入jar包:
具体步骤:
鼠标选中项目右击 → 最后一项(Properties) → 然后选择(Java Build Path) → 选择第三项(Libraries)→ 选择 Add External JARs… → 选择下载好的 jsx.jar文件,导入即可。
图片如下:
1.创建工作簿:
注:
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处添加图片,图片大小占10行3列,只支持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);
代码如下:
package com.LHJ.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, "1314",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, "2019-07-28",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, "2019-07-28",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;
}
}
}
二,图片处理:
(文字水印,图片水印,缩放,补白)
代码如下:
package com.LHJ;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
* 图片工具类, 图片水印,文字水印,缩放,补白等
* @author Carl He
*/
public final class ImageUtils {
/**图片格式:JPG*/
private static final String PICTRUE_FORMATE_JPG = "jpg";
private ImageUtils(){}
/**
* 添加图片水印
* @param targetImg 目标图片路径,如:C://myPictrue//1.jpg
* @param waterImg 水印图片路径,如:C://myPictrue//logo.png
* @param x 水印图片距离目标图片左侧的偏移量,如果x<0, 则在正中间
* @param y 水印图片距离目标图片上侧的偏移量,如果y<0, 则在正中间
* @param alpha 透明度(0.0 -- 1.0, 0.0为完全透明,1.0为完全不透明)
*/
public final static void pressImage(String targetImg, String waterImg, int x, int y, float alpha) {
try {
File file = new File(targetImg);
Image image = ImageIO.read(file);
int width = image.getWidth(null);
int height = image.getHeight(null);
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufferedImage.createGraphics();
g.drawImage(image, 0, 0, width, height, null);
Image waterImage = ImageIO.read(new File(waterImg)); // 水印文件
int width_1 = waterImage.getWidth(null);
int height_1 = waterImage.getHeight(null);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
int widthDiff = width - width_1;
int heightDiff = height - height_1;
if(x < 0){
x = widthDiff / 2;
}else if(x > widthDiff){
x = widthDiff;
}
if(y < 0){
y = heightDiff / 2;
}else if(y > heightDiff){
y = heightDiff;
}
g.drawImage(waterImage, x, y, width_1, height_1, null); // 水印文件结束
g.dispose();
ImageIO.write(bufferedImage, PICTRUE_FORMATE_JPG, file);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 添加文字水印
* @param targetImg 目标图片路径,如:C://myPictrue//1.jpg
* @param pressText 水印文字, 如:中国证券网
* @param fontName 字体名称, 如:宋体
* @param fontStyle 字体样式,如:粗体和斜体(Font.BOLD|Font.ITALIC)
* @param fontSize 字体大小,单位为像素
* @param color 字体颜色
* @param x 水印文字距离目标图片左侧的偏移量,如果x<0, 则在正中间
* @param y 水印文字距离目标图片上侧的偏移量,如果y<0, 则在正中间
* @param alpha 透明度(0.0 -- 1.0, 0.0为完全透明,1.0为完全不透明)
*/
public static void pressText(String targetImg, String pressText, String fontName, int fontStyle, int fontSize, Color color, int x, int y, float alpha) {
try {
File file = new File(targetImg);
Image image = ImageIO.read(file);
int width = image.getWidth(null);
int height = image.getHeight(null);
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufferedImage.createGraphics();
g.drawImage(image, 0, 0, width, height, null);
g.setFont(new Font(fontName, fontStyle, fontSize));
g.setColor(color);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
int width_1 = fontSize * getLength(pressText);
int height_1 = fontSize;
int widthDiff = width - width_1;
int heightDiff = height - height_1;
if(x < 0){
x = widthDiff / 2;
}else if(x > widthDiff){
x = widthDiff;
}
if(y < 0){
y = heightDiff / 2;
}else if(y > heightDiff){
y = heightDiff;
}
g.drawString(pressText, x, y + height_1);
g.dispose();
ImageIO.write(bufferedImage, PICTRUE_FORMATE_JPG, file);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取字符长度,一个汉字作为 1 个字符, 一个英文字母作为 0.5 个字符
* @param text
* @return 字符长度,如:text="中国",返回 2;text="test",返回 2;text="中国ABC",返回 4.
*/
public static int getLength(String text) {
int textLength = text.length();
int length = textLength;
for (int i = 0; i < textLength; i++) {
if (String.valueOf(text.charAt(i)).getBytes().length > 1) {
length++;
}
}
return (length % 2 == 0) ? length / 2 : length / 2 + 1;
}
/**
* 图片缩放
* @param filePath 图片路径
* @param height 高度
* @param width 宽度
* @param bb 比例不对时是否需要补白
*/
public static void resize(String filePath, int height, int width, boolean bb) {
try {
double ratio = 0; //缩放比例
File f = new File(filePath);
BufferedImage bi = ImageIO.read(f);
Image itemp = bi.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH);
//计算比例
if ((bi.getHeight() > height) || (bi.getWidth() > width)) {
if (bi.getHeight() > bi.getWidth()) {
ratio = (new Integer(height)).doubleValue() / bi.getHeight();
} else {
ratio = (new Integer(width)).doubleValue() / bi.getWidth();
}
AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
itemp = op.filter(bi, null);
}
if (bb) {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, width, height);
if (width == itemp.getWidth(null))
g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2, itemp.getWidth(null), itemp.getHeight(null), Color.white, null);
else
g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0, itemp.getWidth(null), itemp.getHeight(null), Color.white, null);
g.dispose();
itemp = image;
}
ImageIO.write((BufferedImage) itemp, "jpg", f);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
pressImage("C://pic//jpg", "C://pic//test.gif", 5000, 5000, 0f);
pressText("C://pic//jpg", "旺仔之印", "宋体", Font.BOLD|Font.ITALIC, 20, Color.BLACK, 0, 0, 8f);
resize("C://pic//4.jpg", 1000, 500, true);
}
}