java中后台导出excel的话,有两种方案,一是使用poi(不过由于是windows版本的,存在不兼容,但功能更多,更强大),而是使用jxl(纯java编写,不过兼容,简单一些),可以设置输出的excel横向还是竖向、A4纸还是A3纸的尺寸大小。由于只需要简单的导出excel,所以选择jxl工具,只需要下载一个jar就可以了jxl.jar.
以下是我的测试类,这是一个工具类,可以直接拿来使用:
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
/**
* Excel文件工具类
*
* @author Administrator
*
*/
public class ExcelUtils {
/**
* 将实体类的信息写入Excel文件
*
* @param fileName
* excel文件名称 如:文件1.excel
* @param list
* 实体类集合
* @param titles
* excel标题名称
* @param columnLength
* 标题名称宽度
* @param fileds
* 对应标题所填充的实体类信息(属性名)
* @throws IOException
* @throws WriteException
* @throws SecurityException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> void writeExcel(String fileName, List<T> list,
String[] titles, int[] columnLength, String[] fileds)
throws IOException, WriteException, NoSuchMethodException,
SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
// 首先要使用Workbook类的工厂方法创建一个可写入的工作薄(Workbook)对象
WritableWorkbook wwb = Workbook.createWorkbook(new File(fileName));
if (wwb != null) {
// 创建一个可写入的工作表
// Workbook的createSheet方法有两个参数,第一个是工作表的名称,第二个是工作表在工作薄中的位置
WritableSheet ws = wwb.createSheet("sheet1", 0);
/*
* 表头单元格样式的设定 WritableFont.createFont("宋体"):设置字体为宋体 12:设置字体大小
* WritableFont.BOLD:设置字体加粗(BOLD:加粗 NO_BOLD:不加粗) false:设置非斜体
* UnderlineStyle.NO_UNDERLINE:没有下划线 Colour.BLACK 字体颜色 黑色
*/
WritableFont titleFont = new WritableFont(
WritableFont.createFont("宋体"), 12, WritableFont.BOLD,
false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
WritableCellFormat titleCellFormat = new WritableCellFormat(
titleFont);
// 字休居中
titleCellFormat.setAlignment(Alignment.CENTRE);
// 设置单元格背景色:表体为白色
titleCellFormat.setBackground(Colour.WHITE);
// 整个表格线为细线、黑色
titleCellFormat.setBorder(Border.ALL, BorderLineStyle.THIN,
Colour.BLACK);
WritableFont contentFont = new WritableFont(
WritableFont.createFont("宋体"), 10, WritableFont.NO_BOLD,
false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
WritableCellFormat contentCellFormat = new WritableCellFormat(
contentFont);
// 字休居中
contentCellFormat.setAlignment(Alignment.CENTRE);
// 设置单元格背景色:表体为白色
contentCellFormat.setBackground(Colour.WHITE);
// 整个表格线为细线、黑色
contentCellFormat.setBorder(Border.ALL, BorderLineStyle.THIN,
Colour.BLACK);
for (int i = 0; i < titles.length; i++) {
ws.setColumnView(i, columnLength[i]); // 设置列的宽度
Label label = new Label(i, 0, titles[i], titleCellFormat);
ws.addCell(label);
}
// 填充实体类的基本信息
for (int j = 0; list != null && !list.isEmpty() && j < list.size(); j++) {
T t = list.get(j);
Class clazz = t.getClass();
String[] contents = new String[fileds.length];
for (int i = 0; fileds != null && i < fileds.length; i++) {
String filedName = toUpperCaseFirstOne(fileds[i]);
Method method = clazz.getMethod(filedName);
method.setAccessible(true);
Object obj = method.invoke(t);
String str = String.valueOf(obj);
if (str == null || str.equals("null"))
str = "";
contents[i] = str;
}
for (int n = 0; n < contents.length; n++) {
// 这里需要注意的是,在Excel中,第一个参数表示列,第二个表示行
Label labelC = new Label(n, j + 1, contents[n],
contentCellFormat);
// 将生成的单元格添加到工作表中
ws.addCell(labelC);
}
}
// 从内存中写入文件中
wwb.write();
// 关闭资源,释放内存
wwb.close();
}
}
/**
* 将第一个字母转换为大写字母并和get拼合成方法
*
* @param origin
* @return
*/
private static String toUpperCaseFirstOne(String origin) {
StringBuffer sb = new StringBuffer(origin);
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
sb.insert(0, "get");
return sb.toString();
}
public static void main(String[] args) throws WriteException,
NoSuchMethodException, SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException, IOException {
List<User> list = new ArrayList<User>();// 获取数据列表
User oneUser = new User();
oneUser.setName("测试");
list.add(oneUser);
String[] titles = new String[] { "姓名" };// 设置列中文名
int columnLength[] = { 10, 10, 10 };// 设置列宽
String fileds[] = new String[] { "name" };// 设置列英文名
ExcelUtils.writeExcel("D:\\ceshi.xls", list, titles, columnLength,
fileds);
}
}
完整的测试例子已经上传到下载频道,传送门在此:java 导出excel工具类(jxl)
java中使用jxl导出excel表格的工具类
2014年12月26日 Java 暂无评论 阅读 72 views 次
这个是同事写的一个导出excel的工具类,具体说明注释中都有,我就不具体说明了,工具类代码如下:
调用示例
package com.core.util;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
/**
* Excel文件工具类
*
* @author Administrator
*
*/
publicclass ExcelUtils {
/**
* 将实体类的信息写入Excel文件
* @param fileName excel文件名称 如:文件1.excel
* @param list 实体类集合
* @param titles excel标题名称
* @param columnLength 标题名称宽度
* @param fileds 对应标题所填充的实体类信息(属性名)
* @throws IOException
* @throws WriteException
* @throws SecurityException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
@SuppressWarnings({"unchecked","rawtypes"})
publicstatic <T> void writeExcel(String fileName,List<T> list,String[] titles,int[] columnLength,String[] fileds) throws IOException, WriteException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
//首先要使用Workbook类的工厂方法创建一个可写入的工作薄(Workbook)对象
WritableWorkbook wwb = Workbook.createWorkbook(newFile(fileName));
if(wwb!=null){
//创建一个可写入的工作表
//Workbook的createSheet方法有两个参数,第一个是工作表的名称,第二个是工作表在工作薄中的位置
WritableSheet ws = wwb.createSheet("sheet1", 0);
/*
* 表头单元格样式的设定
* WritableFont.createFont("宋体"):设置字体为宋体
* 12:设置字体大小
* WritableFont.BOLD:设置字体加粗(BOLD:加粗 NO_BOLD:不加粗)
* false:设置非斜体
* UnderlineStyle.NO_UNDERLINE:没有下划线
* Colour.BLACK 字体颜色 黑色
*/
WritableFont titleFont = newWritableFont(WritableFont.createFont("宋体"), 12, WritableFont.BOLD, false,UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
WritableCellFormat titleCellFormat = newWritableCellFormat(titleFont);
//字休居中
titleCellFormat.setAlignment(Alignment.CENTRE);
//设置单元格背景色:表体为白色
titleCellFormat.setBackground(Colour.WHITE);
//整个表格线为细线、黑色
titleCellFormat.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
WritableFont contentFont = newWritableFont(WritableFont.createFont("宋体"), 10, WritableFont.NO_BOLD, false,UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
WritableCellFormat contentCellFormat = newWritableCellFormat(contentFont);
//字休居中
contentCellFormat.setAlignment(Alignment.CENTRE);
//设置单元格背景色:表体为白色
contentCellFormat.setBackground(Colour.WHITE);
//整个表格线为细线、黑色
contentCellFormat.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
for(int i = 0; i < titles.length; i++) {
ws.setColumnView(i, columnLength[i]); //设置列的宽度
Label label = newLabel(i, 0, titles[i], titleCellFormat);
ws.addCell(label);
}
//填充实体类的基本信息
for(int j=0;list!=null&&!list.isEmpty()&&j<list.size();j++){
T t = list.get(j);
Class clazz=t.getClass();
String[] contents=newString[fileds.length];
for(int i = 0; fileds!=null && i < fileds.length; i++) {
String filedName=toUpperCaseFirstOne(fileds[i]);
Method method=clazz.getMethod(filedName);
method.setAccessible(true);
Object obj=method.invoke(t);
String str=String.valueOf(obj);
if(str==null||str.equals("null"))
str="";
contents[i]=str;
}
for(int n=0;n<contents.length;n++){
//这里需要注意的是,在Excel中,第一个参数表示列,第二个表示行
Label labelC = newLabel(n, j+1,contents[n],contentCellFormat);
//将生成的单元格添加到工作表中
ws.addCell(labelC);
}
}// =========在sheet初始化之后: 设置纸张大小、横向打印=============
WritableSheet sheet = wwb.getSheet(0);
SheetSettings setting = sheet.getSettings();
setting.setOrientation(PageOrientation.LANDSCAPE); // 横向
// ④用纸的大小
setting.setPaperSize(PaperSize.A3);
// ⑥打印开始页号
setting.setPageStart(1);
// =======================================================
//从内存中写入文件中
wwb.write();
//关闭资源,释放内存
wwb.close();
}
}
/**
* 将第一个字母转换为大写字母并和get拼合成方法
* @param origin
* @return
*/
privatestatic String toUpperCaseFirstOne(String origin){
StringBuffer sb = newStringBuffer(origin);
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
sb.insert(0,"get");
returnsb.toString();
}
}
调用示例
List<User> list=userService.getAllUser();//获取数据列表
String[] titles = newString[]{"姓名","年龄","性别"};//设置列中文名
int columnLength[] = {10,10,10};//设置列宽
String fileds[]=newString[]{"name","age","sex"};//设置列英文名
ExcelUtils.writeExcel(fileName, list, titles, columnLength, fileds);
如果你是使用ajax的话,可以在success中,写一个方法,让浏览器弹出刚才生成的excel文件,只需要生成的路径保持相同即可,
,生成的文件你可以放到项目中,新建一个文件夹:download:
// 获取当前用户名
String fileName = "bank_wage";
String filePath = ConfigCaptain.getInstance().getWebRootPath()
+ File.separator + "download";
如下:
<script type="text/javascript">
function downloadWagePdf(){
//var date = document.getElementById("wageDate").value;
var usekey="<%=session.getAttribute("USERID")%>";
var pdfFilePath = "<%=basePath%>" + "WebRoot\\download\\"
+ "bank_wage" + ".xls";
window.open(pdfFilePath);
/* window.location.href=pdfFilePath; */
}
</script>
============================分割线=========================================================
注:后面有一个需求是导出的excel,每一整行都要有下划线,如果给某个数据增加下划线,但空白处,就需要每个都添加一个下划线,势必导致代码很繁琐,所以想到在每行数据的下面添加一行:这一行只有上方的边框,这样使用循环遍历就简单的多了,如下:
// ===================添加上划线===================
for (int i = 0; i < 9; i++) {
Label label = new Label(i, number * LENGTHROWS + 47, "", rowUnderLine);
medicalSheet.addCell(label);
}
还有:jxl的设置打印范围的方法(这个实在2.6的jar包有,1.0之前的没有,所以需要下载最新的jar包:网址如下:http://www.manyjar.com/search/jxl.html):
jxl. SheetSettings.setPrintArea( int firstCol, int firstRow, int lastCol, int lastRow) 其实就是列的方向:从0到末尾的列,行:从0到末尾的行,类似于经纬度。
我的完整工具类代码如下:
package rms.util.excelreportUtil;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.context.support.StaticApplicationContext;
import com.lowagie.text.PageSize;
import rms.config.ConfigCaptain;
import rms.data.BankWageMonth;
import rms.param.PositionRank;
import rms.util.FileUtil;
import rms.util.LogUtil;
import jxl.SheetSettings;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.PageOrientation;
import jxl.format.PaperSize;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
/**
*/
public class MedicalTreatExcelUtil {
static int LENGTHROWS = 55;// 一个excel占据的行数
static int PAGESIZE = 200;// 一个sheet里面有200页数据
/**
*
*
* @param fileName
* excel文件名称 如:文件1.excel
* @param list
* 实体类集合
* @param titles
* excel标题名称
* @param columnLength
* 标题名称宽度
* @param fileds
* 对应标题所填充的实体类信息(属性名)
* @throws IOException
* @throws WriteException
* @throws SecurityException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> void writeMedicalExcel(File file, String fileName, List<T> medicalList, String[] fileds,
String wageDate) throws IOException, WriteException, NoSuchMethodException, SecurityException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// 首先要使用Workbook类的工厂方法创建一个可写入的工作薄(Workbook)对象
FileUtil.createFileDire(file.getAbsolutePath());
// if (!file.getName().toLowerCase().endsWith(".pdf")) {
file = new File(file.getAbsolutePath() + File.separator + fileName + ".xls");
WritableWorkbook wwb = Workbook.createWorkbook(file);
// 判断数据源,分成几个sheet进行渲染数据
if (wwb != null) {
int[] sheetSAndNumber = new int[2];// 分成多少个sheets
// 根据数据源获取需要设置多少个sheet
sheetSAndNumber = generSheets(medicalList.size(), PAGESIZE);
for (int pageNumber = 0; pageNumber < sheetSAndNumber[0]; pageNumber++) {
// 拆分数据源,分会某个页面的数据
List<T> medicalPageList = createList(medicalList, PAGESIZE, pageNumber);
// 绘制一个excel的数据
drawOneSheet(medicalPageList, fileds, wwb, pageNumber, sheetSAndNumber);
}
}
// 从内存中写入文件中
wwb.write();
// 关闭资源,释放内存
wwb.close();
}
/**
* 绘制一个excel的数据
*
* @param medicalList
* @param fileds
* @param wwb
* @throws WriteException
* @throws NoSuchMethodException
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws RowsExceededException
* @throws IOException
*/
private static <T> void drawOneSheet(List<T> medicalList, String[] fileds, WritableWorkbook wwb, int pageNumber,
int[] lastNumber) throws WriteException, NoSuchMethodException, IllegalAccessException,
InvocationTargetException, RowsExceededException, IOException {
// 创建一个可写入的工作表
// Workbook的createSheet方法有两个参数,第一个是工作表的名称,第二个是工作表在工作薄中的位置
WritableSheet medicalSheet = wwb.createSheet("第" + (pageNumber + 1) + "个单", pageNumber);
/*
* 表头单元格样式的设定 WritableFont.createFont("宋体"):设置字体为宋体 12:设置字体大小
* WritableFont.BOLD:设置字体加粗(BOLD:加粗 NO_BOLD:不加粗) false:设置非斜体
* UnderlineStyle.NO_UNDERLINE:没有下划线 Colour.BLACK 字体颜色 黑色
*/
// 标题的字体
WritableFont titleFont = new WritableFont(WritableFont.createFont("宋体"), 16, WritableFont.NO_BOLD, false,
UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
WritableFont titleFuFont = new WritableFont(WritableFont.createFont("宋体"), 14, WritableFont.NO_BOLD, false,
UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
WritableCellFormat titleCellFormat = new WritableCellFormat(titleFont);
// 字休居中
titleCellFormat.setAlignment(Alignment.CENTRE);
// 设置单元格背景色:表体为白色
titleCellFormat.setBackground(Colour.WHITE);
// 整个表格线为细线、黑色
titleCellFormat.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
// 正文内容的字体:
WritableFont contentFont = new WritableFont(WritableFont.createFont("宋体"), 11, WritableFont.NO_BOLD, false,
UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
// 单位全称很长,需要缩小字体
WritableFont danweiquanchenFont = new WritableFont(WritableFont.createFont("宋体"), 8, WritableFont.BOLD, false,
UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
// 填写的cell的格式,比标题小一号
WritableCellFormat danweiFormat = new WritableCellFormat(danweiquanchenFont);
// 字休居中
danweiFormat.setAlignment(Alignment.LEFT);
// 设置单元格背景色:表体为白色
danweiFormat.setBackground(Colour.WHITE);
// 整个表格线为细线、黑色
danweiFormat.setBorder(Border.NONE, BorderLineStyle.THIN, Colour.BLACK);
// 填写的cell字体,比标题小一号
WritableFont contentWordFont = new WritableFont(WritableFont.createFont("宋体"), 10, WritableFont.BOLD, false,
UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
// 填写的cell的格式,比标题小一号
WritableCellFormat WordFormat = new WritableCellFormat(contentWordFont);
// 字休居中
WordFormat.setAlignment(Alignment.LEFT);
// 设置单元格背景色:表体为白色
WordFormat.setBackground(Colour.WHITE);
// 整个表格线为细线、黑色
WordFormat.setBorder(Border.NONE, BorderLineStyle.THIN, Colour.BLACK);
WritableCellFormat contentCellFormat = new WritableCellFormat(contentFont);
// 字休居中
contentCellFormat.setAlignment(Alignment.CENTRE);
// 设置单元格背景色:表体为白色
contentCellFormat.setBackground(Colour.WHITE);
// 整个表格线为细线、黑色
contentCellFormat.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
// 添加右侧整条的下划线
WritableCellFormat rowRightLine = new WritableCellFormat(titleFont);
// 字休居中
rowRightLine.setAlignment(Alignment.RIGHT);
// 设置单元格背景色:表体为白色
rowRightLine.setBackground(Colour.WHITE);
// 整个表格线为细线、黑色
rowRightLine.setBorder(Border.RIGHT, BorderLineStyle.THIN, Colour.BLACK);
// 添加上方整条的下划线
WritableCellFormat rowUnderLine = new WritableCellFormat(titleFont);
// 字休居中
rowUnderLine.setAlignment(Alignment.CENTRE);
// 设置单元格背景色:表体为白色
rowUnderLine.setBackground(Colour.WHITE);
// 整个表格线为细线、黑色
rowUnderLine.setBorder(Border.TOP, BorderLineStyle.THIN, Colour.BLACK);
// 中间的标题
WritableCellFormat titleTopFormatCen = new WritableCellFormat(titleFuFont);
// 字休居中
titleTopFormatCen.setAlignment(Alignment.CENTRE);
// 设置单元格背景色:表体为白色
titleTopFormatCen.setBackground(Colour.WHITE);
// 整个表格线为细线、黑色
titleTopFormatCen.setBorder(Border.NONE, BorderLineStyle.NONE, Colour.AUTOMATIC);
// 左侧标题的字体
WritableCellFormat titleTopFormatLeft = new WritableCellFormat(contentFont);
// 字休居中
titleTopFormatLeft.setAlignment(Alignment.LEFT);
// 设置单元格背景色:表体为白色
titleTopFormatLeft.setBackground(Colour.WHITE);
// 整个表格线为细线、黑色
titleTopFormatLeft.setBorder(Border.NONE, BorderLineStyle.NONE, Colour.AUTOMATIC);
// 右侧标题的字体
WritableCellFormat titleTopFormatRight = new WritableCellFormat(contentFont);
// 字休居中
titleTopFormatRight.setAlignment(Alignment.LEFT);
// 设置单元格背景色:表体为白色
titleTopFormatRight.setBackground(Colour.WHITE);
// 整个表格线为细线、黑色
titleTopFormatRight.setBorder(Border.NONE, BorderLineStyle.NONE, Colour.AUTOMATIC);
// excel主题内容填充数据
List<String[]> contentList = new ArrayList<String[]>();
for (int j = 0; medicalList != null && !medicalList.isEmpty() && j < medicalList.size(); j++) {
T t = medicalList.get(j);
Class<? extends Object> clazz = t.getClass();
String[] contents = new String[fileds.length];
for (int i = 0; fileds != null && i < fileds.length; i++) {
// 第一列为序号:自增,需要特殊处理
String filedName = toUpperCaseFirstOne(fileds[i]);
Method method = clazz.getMethod(filedName);
method.setAccessible(true);
Object obj = method.invoke(t);
String str = String.valueOf(obj);
if (str == null || str.equals("null"))
str = "";
contents[i] = str;
}
// 每个用户都需要导出一页excel内容,保存在hashmap中
contentList.add(contents);
}
// 如果假设430,每页200,分成3页的话,第三页的数据为30,需要特殊处理
int everyPageSize = 0;// 每个sheet的记录数
if (pageNumber + 1 == lastNumber[0]) {
if (lastNumber[1] != 0) {
everyPageSize = lastNumber[1];
} else {
everyPageSize = PAGESIZE;
}
} else {
everyPageSize = PAGESIZE;
}
for (int number = 0; number < everyPageSize; number++) {
String[] conStrs = contentList.get(number);
// ========第一行:=====
Label labelTopFisrtTitle = new Label(4, number * LENGTHROWS + 0, "上证", titleTopFormatCen);
medicalSheet.addCell(labelTopFisrtTitle);
// ========第二行: ===========
Label labelTopSecondTitle = new Label(4, number * LENGTHROWS + 1, "单\n", titleTopFormatCen);
medicalSheet.addCell(labelTopSecondTitle);
// =======添加下划线==============
for (int i = 0; i < 9; i++) {
Label label = new Label(i, number * LENGTHROWS + 3, "", rowUnderLine);
medicalSheet.addCell(label);
}
}
// =============================================================
// =========在sheet初始化之后: 设置纸张大小、横向打印=============
WritableSheet sheet = wwb.getSheet(pageNumber);
// 两个盖章的地方需要特殊处理,所以需要保存200个这时候的位置进行遍历判断
for (int i = 0; i < everyPageSize; i++) {
for (int cou = i * LENGTHROWS; cou < i * LENGTHROWS + LENGTHROWS; cou++) {
sheet.setRowView(cou, 269, false); // 设置行高
if (cou == i * LENGTHROWS + 23 || cou == i * LENGTHROWS + 37) {
sheet.setRowView(i * LENGTHROWS + 23, 20, false); // 设置行高
sheet.setRowView(i * LENGTHROWS + 37, 20, false); // 设置行高
System.out.println("设置特殊的高度");
}
// 第一标题需要设置高一点
if (cou == i * LENGTHROWS + 0) {
sheet.setRowView(0, 400, false); // 设置行高
System.out.println("设置第一行的高度" + i);
}
System.out.println("第二行数据为" + cou + "第几页:" + i);
}
}
// ---------------------------------------------------
SheetSettings setting = sheet.getSettings();
setting.setOrientation(PageOrientation.PORTRAIT); // 竖向.
setting.setPrintArea(0, 0, 8, LENGTHROWS * everyPageSize);
// ④用纸的大小
// setting.setPaperSize(PaperSize.A4);
// ⑥打印开始页号
// setting.setPageStart(1);
// =======================================================
}
// 专业技术只能存在一个
public static String isProfrePostionRank(String s) {
/*
* 此方法有两个参数,第一个是要查找的字符串数组,第二个是要查找的字符或字符串
*/
String[] strs = { "15", "16", "17", "18", "19", "20", "21", "22" };
for (int i = 0; i < strs.length; i++) {
if (s.equals(strs[i])) {
return PositionRank.getNameByCode(s);// 查找到了就返回真,不在继续查询
}
}
return "";
}
// 军和只能存在一个
public static String isJunPostionRank(String s) {
/*
* 此方法有两个参数,第一个是要查找的字符串数组,第二个是要查找的字符或字符串
*/
String[] strs = { "1", "2", "3", "4", "5", "6", "7", "30", "31", "32", "33", "41" };
for (int i = 0; i < strs.length; i++) {
if (s.equals(strs[i])) {
return PositionRank.getNameByCode(s);// 查找到了就返回真,不在继续查询
}
}
return "";
}
/**
* 将第一个字母转换为大写字母并和get拼合成方法
*
* @param origin
* @return
*/
private static String toUpperCaseFirstOne(String origin) {
StringBuffer sb = new StringBuffer(origin);
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
sb.insert(0, "get");
return sb.toString();
}
/**
* 由于数据过多,一个sheet里面,放200条数据
*
* @param datas
* @param pageSize
* @return
*/
public static int[] generSheets(int datas, int pageSize) {
int[] countAndNumber = new int[2];
int pageCounts = 0;// 每一页包含的记录数
int countSheet = datas / pageSize;
int countSheetAdd = datas % PAGESIZE;
if (countSheetAdd != 0) {
++countSheet;
pageCounts = countSheetAdd;// 最后一页如果不足pagsize就需要保留
}
LogUtil.info("打印:单分成了" + countSheet + "sheet");
countAndNumber[0] = countSheet;
countAndNumber[1] = pageCounts;
return countAndNumber;
}
/**
* //将list拆分为多个数据源,返回某个页面的数据
*
* @param <T>
* @param targe
* @param size
* @return
*/
public static <T> List<T> createList(List<T> targe, int size, int pageNumber) {
List<List<T>> listArr = new ArrayList<List<T>>();
// 获取被拆分的数组个数
int arrSize = targe.size() % size == 0 ? targe.size() / size : targe.size() / size + 1;
for (int i = 0; i < arrSize; i++) {
List<T> sub = new ArrayList<T>();
// 把指定索引数据放入到list中
for (int j = i * size; j <= size * (i + 1) - 1; j++) {
if (j <= targe.size() - 1) {
sub.add(targe.get(j));
}
}
listArr.add(sub);
}
return listArr.get(pageNumber);
}
// 去掉日期的后面的日子-
public static String removeDay(String dateStr) {
if (dateStr.equalsIgnoreCase("")) {
return "";
} else {
String[] strPar = dateStr.split("-");
String returnString = strPar[0] + "-" + strPar[1];
return returnString;
}
}
}
1.如果还要求列设置自动列宽,可以使用如下代码:
// 设置自动列宽
CellView cellView = new CellView();
cellView.setAutosize(true); // 设置自动大小
sheet.setColumnView(cou, cellView);// 根据内容自动设置列宽
2.导出的excel需要让文字在单元格垂直居中,但发现设置的属性没有发挥作用,经过调试发现,可以在元数据中填上空格或者换行符,当读取的时候,就可以有空的效果,将文字顶上去,多处一行空行,如下代码:
medMonth.setIdenti(" " + object[2] + "\n ");
// medMonth.setMedicalIdenti(" " + object[3] +
// "\n ");
medMonth.setMedicalIdenti(" " + object[3] + "\n ");
medMonth.setAssignTime(" 2017-03\n ");