xlsjava
A. 如何在java中做excel表
很简单,这有代码:代码里面数据库访问对象自己写,用到第三方架包:
poi-2.5-final-20040302.jar;
poi-contrib-2.5-final-20040302.jar
poi-scratchpad-2.5-final-20040302.jar
自己去网上下吧
//处理类
public class CountExcel {
/**
* 数据库操作类,自己写吧。。。
*/
private OperData jdbc /*自己写*/;
/**
* 创建excel,返回excel的存放地址
*
* @param title
* 标题
* @param sql
* 查询语句
* @param path
* excel的存放路径(物理地址)
* @param titlename
* 报表的名字
* @return 路径
*/
public String createExcelForAssess(String[] title, String sql, String path,
String titlename) throws Exception {
GregorianCalendar c = new GregorianCalendar();
StringBuffer excelUrl = new StringBuffer();
java.util.Date now = c.getTime();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
String strNow = format.format(now);
excelUrl.append(path).append(File.separator).append("te_").append(
strNow).append(".xls");
// excel的表头
Vector vcCol = new Vector();
if (title == null || title.length < 1)
return "";
for (int i = 0; i < title.length; i++) {
vcCol.add(title[i]);
}
int[] align = new int[vcCol.size()];
int[] num = new int[vcCol.size()];
for (int i = 0; i < vcCol.size(); i++) {
align[i] = 2;
num[i] = 0;
}
Vector vc = getqueryrest(sql);
ExcelReport excel = new ExcelReport();
excel.setExcelFile(excelUrl.toString());
excel.setCols(vcCol.size());
excel.createCaption(titlename);
excel.createColumnCaption(vcCol);
excel.createBody(vc, align, num);
excel.createPage(5);
excel.createFile();
return excelUrl.toString();
}
/**
* 查询结果集
*
* @param sql传入查询的sql语句
* @return Vector
* @throws SQLException
*/
public Vector getqueryrest(String sql) throws SQLException {
Vector vc = new Vector();
//数据库查询,返回的list里面存的是数据的pojo对象
//List list = jdbc.getQueryResult(sql);
if (list != null && list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
String[] info = (String[]) list.get(i);
for (int j = 0; j < info.length; j++) {
vc.add(info[j]);
}
}
}
return vc;
}
}
//工具类
public class ExcelReport{
/**
* EXCEL文件工作区
*/
private HSSFWorkbook wb;
/**
* EXCEL文件SHEET
*/
private HSSFSheet sheet;
/**
* EXCEL文件存放的目录路径
*/
private String excelFile = "";
/**
* 记录当前行数
*/
private int rownum = 0;
/**
* 记录总共列数
*/
private int cols = 0;
/**
* 记录每列的宽度
*/
private int[] length;
/**
* 记录是否已经设定字段数
*/
private boolean flag = false;
/**
* 设置EXCEL文件存放的目录路径,在生成标题,列头前设定
*/
public void setExcelFile(String excelFile){
this.excelFile = excelFile;
}
/**
* 设置EXCEL表的列数,在生成标题,列头前设定
*/
public void setCols(int cols){
this.cols = cols;
if(flag){
if(length.length < cols){
length = getLength(length);
}
}else{
length = new int[cols];
}
flag = true;
}
/**
* 第二次设定字段数,保存第一张表格每列的长度
*/
private int[] getLength(int[] arr){
int[] temp = new int[cols];
for(int i=0;i<arr.length;i++){
temp[i] = arr[i];
}
return temp;
}
/**
* 初始化EXCEL报表类
*/
public ExcelReport(){
wb = new HSSFWorkbook();
sheet = wb.createSheet("new sheet");
}
/**
* 生成标题
* @param caption 标题头
*/
public void createCaption(String caption){
//生成标题行
HSSFRow row = sheet.createRow((short)rownum);
//生成标题单元格
HSSFCell cell = row.createCell((short)0);
//生成标题单元格样式
HSSFCellStyle style = wb.createCellStyle();
//设定标题字体
HSSFFont font = wb.createFont();
font.setFontHeightInPoints((short)14);
font.setFontName("新宋体");
font.setColor(HSSFColor.BLACK.index);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
style.setFont(font);
//设定标题框格式
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBottomBorderColor(HSSFColor.BLACK.index);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setLeftBorderColor(HSSFColor.BLACK.index);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setRightBorderColor(HSSFColor.BLACK.index);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setTopBorderColor(HSSFColor.BLACK.index);
//设定对齐方式
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
//设置cell编码解决中文高位字节截断
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
//设定单元格文字合样式
cell.setCellValue(caption);
cell.setCellStyle(style);
for(int i=1;i<cols;i++){
cell = row.createCell((short)i);
cell.setCellStyle(style);
cell.setCellValue("");
}
//设定合并的单元格
sheet.addMergedRegion(new Region(rownum,(short)0,rownum,(short)(cols-1)));
//当前行自增
rownum++;
}
/**
* 生成列头
* @param vc 列头内容
*/
public void createColumnCaption(Vector vc){
//生成列头行
HSSFRow row = sheet.createRow((short)rownum);
//生成了列头格式
HSSFCellStyle style = wb.createCellStyle();
//设定列头字体
HSSFFont font = wb.createFont();
font.setFontHeightInPoints((short)10);
font.setFontName("新宋体");
font.setColor(HSSFColor.BLACK.index);
style.setFont(font);
//设定标题框格式
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBottomBorderColor(HSSFColor.BLACK.index);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setLeftBorderColor(HSSFColor.BLACK.index);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setRightBorderColor(HSSFColor.BLACK.index);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setTopBorderColor(HSSFColor.BLACK.index);
//设定对齐方式
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
//生成列头单元格
HSSFCell cell;
for(int i=0;i<vc.size();i++){
//生成标题单元格
cell = row.createCell((short)i);
//设置cell编码解决中文高位字节截断
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
//设定单元格文字合样式
if(vc.get(i) != null){
cell.setCellValue(vc.get(i).toString());
//记录列头的长度
if(vc.get(i).toString().getBytes().length > length[i]){
length[i] = vc.get(i).toString().getBytes().length;
}
}else{
cell.setCellValue("");
}
cell.setCellStyle(style);
}
rownum++;
}
/**
* 生成合并的列头
* @param vc 列头
* @param colnum 每列要合并的列数,并且所有要合并的列数之和等于总表格列数
*/
public void mergeColumnCaption(Vector vc,int[] colnum){
//生成标题行
HSSFRow row = sheet.createRow((short)rownum);
//生成标题单元格样式
HSSFCellStyle style = wb.createCellStyle();
//设定标题字体
HSSFFont font = wb.createFont();
font.setFontHeightInPoints((short)10);
font.setFontName("新宋体");
font.setColor(HSSFColor.BLACK.index);
style.setFont(font);
//设定标题框格式
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBottomBorderColor(HSSFColor.BLACK.index);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setLeftBorderColor(HSSFColor.BLACK.index);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setRightBorderColor(HSSFColor.BLACK.index);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setTopBorderColor(HSSFColor.BLACK.index);
//设定对齐方式
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
int pos = 0;
HSSFCell cell;
for(int i=0;i<vc.size();i++){
pos = pos + colnum[i];
cell = row.createCell((short)(pos-colnum[i]));
//设置cell编码解决中文高位字节截断
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
//设定单元格文字合样式
cell.setCellStyle(style);
if(vc.get(i) == null){
cell.setCellValue("");
}else{
cell.setCellValue(vc.get(i).toString());
}
for(int j=1;j<colnum[i];j++){
cell = row.createCell((short)(pos-colnum[i]+j));
cell.setCellStyle(style);
cell.setCellValue("");
}
//设定合并的单元格
sheet.addMergedRegion(new Region(rownum,(short)(pos-colnum[i]),rownum,(short)(pos-1)));
}
//当前行自增
rownum++;
}
/**
* 合并行
* @param startrow 起始行
* @param endrow 终止行
* @param column 列数
*/
public void mergeRowCaption(int startrow,int endrow,int column){
sheet.addMergedRegion(new Region(startrow,(short)column,endrow,(short)column));
}
/**
* 生成表格主体
* @param vc 表格内容
* @param align 每列的对齐方式,1为左,2为中,3为右,数组长度要等于表格列数
* @param num 每列的数据类型,0为字符串,1为数字
*/
public void createBody(Vector vc,int[] align,int[] num){
int rows = vc.size() / cols;
//设定表格字体
HSSFFont font = wb.createFont();
font.setFontHeightInPoints((short)10);
font.setFontName("新宋体");
font.setColor(HSSFColor.BLACK.index);
font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
HSSFRow row;
HSSFCell cell;
//设定数据格式
HSSFDataFormat df = wb.createDataFormat();
//生成了左对齐表格格式
HSSFCellStyle styleLeft = wb.createCellStyle();
styleLeft.setFont(font);
styleLeft.setBorderBottom(HSSFCellStyle.BORDER_THIN);
styleLeft.setBottomBorderColor(HSSFColor.BLACK.index);
styleLeft.setBorderLeft(HSSFCellStyle.BORDER_THIN);
styleLeft.setLeftBorderColor(HSSFColor.BLACK.index);
styleLeft.setBorderRight(HSSFCellStyle.BORDER_THIN);
styleLeft.setRightBorderColor(HSSFColor.BLACK.index);
styleLeft.setBorderTop(HSSFCellStyle.BORDER_THIN);
styleLeft.setTopBorderColor(HSSFColor.BLACK.index);
styleLeft.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
styleLeft.setAlignment(HSSFCellStyle.ALIGN_LEFT);
styleLeft.setDataFormat(df.getFormat("##################.00"));
//生成居中对齐表格格式
HSSFCellStyle styleCenter = wb.createCellStyle();
styleCenter.setFont(font);
styleCenter.setBorderBottom(HSSFCellStyle.BORDER_THIN);
styleCenter.setBottomBorderColor(HSSFColor.BLACK.index);
styleCenter.setBorderLeft(HSSFCellStyle.BORDER_THIN);
styleCenter.setLeftBorderColor(HSSFColor.BLACK.index);
styleCenter.setBorderRight(HSSFCellStyle.BORDER_THIN);
styleCenter.setRightBorderColor(HSSFColor.BLACK.index);
styleCenter.setBorderTop(HSSFCellStyle.BORDER_THIN);
styleCenter.setTopBorderColor(HSSFColor.BLACK.index);
styleCenter.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
styleCenter.setAlignment(HSSFCellStyle.ALIGN_CENTER);
styleCenter.setDataFormat(df.getFormat("##################.00"));
//生成右对齐表格格式
HSSFCellStyle styleRight = wb.createCellStyle();
styleRight.setFont(font);
styleRight.setBorderBottom(HSSFCellStyle.BORDER_THIN);
styleRight.setBottomBorderColor(HSSFColor.BLACK.index);
styleRight.setBorderLeft(HSSFCellStyle.BORDER_THIN);
styleRight.setLeftBorderColor(HSSFColor.BLACK.index);
styleRight.setBorderRight(HSSFCellStyle.BORDER_THIN);
styleRight.setRightBorderColor(HSSFColor.BLACK.index);
styleRight.setBorderTop(HSSFCellStyle.BORDER_THIN);
styleRight.setTopBorderColor(HSSFColor.BLACK.index);
styleRight.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
styleRight.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
styleRight.setDataFormat(df.getFormat("##################.00"));
for (int i = 0;i < rows; i++){
// 创建新行
row = sheet.createRow((short)(rownum));
for (int j = 0;j < cols; j++){
// 创建一个单元格
cell = row.createCell((short)j);
//设置cell编码解决中文高位字节截断
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
//设置cell字符类型的值
if(vc.get(i*cols+j) == null){
cell.setCellValue("");
}else{
if(num[j] == 0){
cell.setCellValue(vc.get(i*cols+j).toString());
}else{
cell.setCellValue(Double.parseDouble(vc.get(i*cols+j).toString()));
}
//记录每列的长度
if(vc.get(i*cols+j).toString().getBytes().length > length[j]){
length[j] = vc.get(i*cols+j).toString().getBytes().length;
}
}
//设定对齐方式
if(align[j] == 1){
cell.setCellStyle(styleLeft);
}
if(align[j] == 2){
cell.setCellStyle(styleCenter);
}
if(align[j] == 3){
cell.setCellStyle(styleRight);
}
}
rownum++;
}
}
/**
* 生成统计结果行
* @param stat 统计结果
* @param align 对齐方式,1为左,2为中,3为右
*/
public void createStat(String stat,int align){
//生成统计结果行
HSSFRow row = sheet.createRow((short)rownum);
//生成统计结果格
HSSFCell cell = row.createCell((short)0);
//生成统计结果单元格样式
HSSFCellStyle style = wb.createCellStyle();
//设定统计结果字体
HSSFFont font = wb.createFont();
font.setFontHeightInPoints((short)10);
font.setFontName("新宋体");
font.setColor(HSSFColor.BLACK.index);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
style.setFont(font);
//设定标题框格式
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBottomBorderColor(HSSFColor.BLACK.index);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setLeftBorderColor(HSSFColor.BLACK.index);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setRightBorderColor(HSSFColor.BLACK.index);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setTopBorderColor(HSSFColor.BLACK.index);
//设定对齐方式
if(align == 1){
style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
}
if(align == 2){
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
}
if(align == 3){
style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
}
//设置cell编码解决中文高位字节截断
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
//设定单元格文字合样式
cell.setCellValue(stat);
cell.setCellStyle(style);
for(int i=1;i<cols;i++){
cell = row.createCell((short)i);
cell.setCellStyle(style);
cell.setCellValue("");
}
//设定合并的单元格
sheet.addMergedRegion(new Region(rownum,(short)0,rownum,(short)(cols-1)));
//当前行自增
rownum++;
}
/**
* 设置页眉
* @param header 页眉内容
* @param align 对齐方式,1为左,2为中,3为右
*/
public void createHeader(String header,int align){
HSSFHeader head = sheet.getHeader();
if(align == 1){
head.setLeft(header);
}
if(align == 2){
head.setCenter(header);
}
if(align == 3){
head.setRight(header);
}
}
/**
* 设置页脚
* @param footer 页脚内容
* @param align 对齐方式,1为左,2为中,3为右
*/
public void createFooter(String footer,int align){
HSSFFooter foot = sheet.getFooter();
if(align == 1){
foot.setLeft(footer);
}
if(align == 2){
foot.setCenter(footer);
}
if(align == 3){
foot.setRight(footer);
}
}
/**
* 设定页脚的页面值
* @param align 对齐方式,1为左,2为中,3为右
*/
public void createPage(int align){
HSSFFooter foot = sheet.getFooter();
if(align == 1){
foot.setLeft("Page:" + HSSFFooter.page() + "/" + HSSFFooter.numPages());
}
if(align == 2){
foot.setCenter("Page:" + HSSFFooter.page() + "/" + HSSFFooter.numPages());
}
if(align == 3){
foot.setRight("Page:" + HSSFFooter.page() + "/" + HSSFFooter.numPages());
}
}
/**
* 生成EXCEL文件
*/
public void createFile() throws Exception{
for(int i=0;i<length.length;i++){
sheet.setColumnWidth((short)i,(short)(length[i]*2*200));
}
FileOutputStream fileOut = new FileOutputStream(excelFile);
wb.write(fileOut);
fileOut.close();
}
}
B. 浅谈JAVA读写Excel的几种途径
读写Excel文件需要使用Excel类库,如Free Spire.XLS for Java.
读取Excel内容:
//创建Workbook对象
Workbookwb=newWorkbook();
//加载一个Excel文档
wb.loadFromFile("C:\Users\Administrator\Desktop\test.xlsx");
//获取第一个工作表
Worksheetsheet=wb.getWorksheets().get(0);
//遍历工作表的每一行
for(inti=1;i<sheet.getLastRow()+1;i++){
//遍历工作的每一列
for(intj=1;j<sheet.getLastColumn()+1;j++){
//输出指定单元格的数据
System.out.print(sheet.get(i,j).getText());
System.out.print(" ");
}
System.out.print(" ");
}
写入内容:
//创建Workbook对象
Workbookwb=newWorkbook();
//加载一个Excel文档
wb.loadFromFile("C:\Users\Administrator\Desktop\test.xlsx");
//获取第一个工作表
Worksheetsheet=wb.getWorksheets().get(0);
//在单元格A1写入新数据
sheet.getCellRange("A1").setText("你好");
//保存文档
wb.saveToFile("写入Excel.xlsx",ExcelVersion.Version2016);
C. 怎样在java中导出xls文件
给你些小例子!用的是poi
package com;
import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class CreateXL {
/**
* 制定EXCEL要存放的文件位置,假定在D盘的test目录下
*/
public static String outputFile="C:/Users/chentx/Desktop/test.xls";
public static void main(String[] args) {
try {
//创建新的Excel工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
//在Excel中建一个工作表,其名为默认值
//如果建造一张为"ucap字段"的工作表,那么语句就是HSSFSheet sheet =workbook.createSheet("ucap字段");
HSSFSheet sheet =workbook.createSheet();
//在索引0的位置创建行(最顶端的行)
HSSFRow row = sheet.createRow(0);
//在索引0的位置创建单元格(左上端)
HSSFCell cell = row.createCell(0);
//定义单元格为字符串类型
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
//在单元格中输入一些内容
cell.setCellValue("field1");
//begin,设置单元格格式-----------------------------------
HSSFFont font = workbook.createFont();
font.setColor(HSSFFont.COLOR_RED);//设置红色
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//设置粗体
//创建格式
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFont(font);
//应用格式
cell.setCellStyle(cellStyle); //设置格式
cell.setCellType(HSSFCell.CELL_TYPE_STRING);//定义单元格为字符串类型
cell.setCellValue("陈天翔霸气");//设置文本内容
//end,------------------------------------------------
//输出文件流
FileOutputStream fOut = new FileOutputStream(outputFile);
//把相应的excel工作表保存到硬盘上
workbook.write(fOut);
fOut.flush();
fOut.close();//关闭文件,操作结束
System.out.println("文件生成完毕....");
} catch (Exception e) {
System.out.println("已运行出错" + e);
}
}
}
/*******************************************************************************************************/
package com;
import java.io.FileInputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class ReadXL {
public static String fileToBeRead="C:/Users/chentx/Desktop/test.xls";
public static void main(String[] args) {
try {
//创建对excel工作表文件的引用
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(fileToBeRead));
/* 创建对工作表的引用,本例按名引用(工作簿名Sheet0)
* HSSFSheet sheet = workbook.getSheet("Sheet0");
* 或者按索引引用
* HssfSheet sheet = workbook.getSheetAt(0);
*/
HSSFSheet sheet = workbook.getSheetAt(0);
//读取左上端单元
HSSFRow row = sheet.getRow(0);
HSSFCell cell = row.getCell(0);
//拿到读出的内容
String mes = cell.getStringCellValue();
System.out.println("拿到的信息:" + mes);
} catch (Exception e) {
e.printStackTrace();
}
}
}
D. java如何输出xls格式的Excel表格文件
有个开源的东东-jxl.jar,可以到http://sourceforge.net/project/showfiles.php?group_id=79926下载。
一.读取Excel文件内容
/**读取Excel文件的内容
* @param file 待读取的文件
* @return
*/
public static String readExcel(File file){
StringBuffer sb = new StringBuffer();
Workbook wb = null;
try {
//构造Workbook(工作薄)对象
wb=Workbook.getWorkbook(file);
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(wb==null)
return null;
//获得了Workbook对象之后,就可以通过它得到Sheet(工作表)对象了
Sheet[] sheet = wb.getSheets();
if(sheet!=null&&sheet.length>0){
//对每个工作表进行循环
for(int i=0;i<sheet.length;i++){
//得到当前工作表的行数
int rowNum = sheet[i].getRows();
for(int j=0;j<rowNum;j++){
//得到当前行的所有单元格
Cell[] cells = sheet[i].getRow(j);
if(cells!=null&&cells.length>0){
//对每个单元格进行循环
for(int k=0;k<cells.length;k++){
//读取当前单元格的值
String cellValue = cells[k].getContents();
sb.append(cellValue+" ");
}
}
sb.append(" ");
}
sb.append(" ");
}
}
//最后关闭资源,释放内存
wb.close();
return sb.toString();
}
二.写入Excel文件
这里有很多格式了,比如文本内容加粗,加上某些颜色等,可以参考jxl的api,同时还推荐一篇不错的文章:http://www.ibm.com/developerworks/cn/java/l-javaExcel/?ca=j-t10
/**生成一个Excel文件
* @param fileName 要生成的Excel文件名
*/
public static void writeExcel(String fileName){
WritableWorkbook wwb = null;
try {
//首先要使用Workbook类的工厂方法创建一个可写入的工作薄(Workbook)对象
wwb = Workbook.createWorkbook(new File(fileName));
} catch (IOException e) {
e.printStackTrace();
}
if(wwb!=null){
//创建一个可写入的工作表
//Workbook的createSheet方法有两个参数,第一个是工作表的名称,第二个是工作表在工作薄中的位置
WritableSheet ws = wwb.createSheet("sheet1", 0);
//下面开始添加单元格
for(int i=0;i<10;i++){
for(int j=0;j<5;j++){
//这里需要注意的是,在Excel中,第一个参数表示列,第二个表示行
Label labelC = new Label(j, i, "这是第"+(i+1)+"行,第"+(j+1)+"列");
try {
//将生成的单元格添加到工作表中
ws.addCell(labelC);
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
}
try {
//从内存中写入文件中
wwb.write();
//关闭资源,释放内存
wwb.close();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
}
三.在一个Excel文件中查找是否包含某一个关键字
/**搜索某一个文件中是否包含某个关键字
* @param file 待搜索的文件
* @param keyWord 要搜索的关键字
* @return
*/
public static boolean searchKeyWord(File file,String keyWord){
boolean res = false;
Workbook wb = null;
try {
//构造Workbook(工作薄)对象
wb=Workbook.getWorkbook(file);
} catch (BiffException e) {
return res;
} catch (IOException e) {
return res;
}
if(wb==null)
return res;
//获得了Workbook对象之后,就可以通过它得到Sheet(工作表)对象了
Sheet[] sheet = wb.getSheets();
boolean breakSheet = false;
if(sheet!=null&&sheet.length>0){
//对每个工作表进行循环
for(int i=0;i<sheet.length;i++){
if(breakSheet)
break;
//得到当前工作表的行数
int rowNum = sheet[i].getRows();
boolean breakRow = false;
for(int j=0;j<rowNum;j++){
if(breakRow)
break;
//得到当前行的所有单元格
Cell[] cells = sheet[i].getRow(j);
if(cells!=null&&cells.length>0){
boolean breakCell = false;
//对每个单元格进行循环
for(int k=0;k<cells.length;k++){
if(breakCell)
break;
//读取当前单元格的值
String cellValue = cells[k].getContents();
if(cellValue==null)
continue;
if(cellValue.contains(keyWord)){
res = true;
breakCell = true;
breakRow = true;
breakSheet = true;
}
}
}
}
}
}
//最后关闭资源,释放内存
wb.close();
return res;
}
四.往Excel中插入图片图标
插入图片的实现很容易,参看以下代码:
/**往Excel中插入图片
* @param dataSheet 待插入的工作表
* @param col 图片从该列开始
* @param row 图片从该行开始
* @param width 图片所占的列数
* @param height 图片所占的行数
* @param imgFile 要插入的图片文件
*/
public static void insertImg(WritableSheet dataSheet, int col, int row, int width,
int height, File imgFile){
WritableImage img = new WritableImage(col, row, width, height, imgFile);
dataSheet.addImage(img);
}
以上代码的注释已经很清楚了,大概也就不用再解释了,我们可以用如下程序验证:
try {
//创建一个工作薄
WritableWorkbook workbook = Workbook.createWorkbook(new File("D:/test1.xls"));
//待插入的工作表
WritableSheet imgSheet = workbook.createSheet("Images",0);
//要插入的图片文件
File imgFile = new File("D:/1.png");
//图片插入到第二行第一个单元格,长宽各占六个单元格
insertImg(imgSheet,0,1,6,6,imgFile);
workbook.write();
workbook.close();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
但是jxl只支持png格式的图片,jpg格式和gif格式都不支持
五.插入页眉页脚
一般的页眉页脚都分为三个部分,左,中,右三部分,利用如下代码可实现插入页眉页脚
/**向Excel中加入页眉页脚
* @param dataSheet 待加入页眉的工作表
* @param left
* @param center
* @param right
*/
public static void setHeader(WritableSheet dataSheet,String left,String center,String right){
HeaderFooter hf = new HeaderFooter();
hf.getLeft().append(left);
hf.getCentre().append(center);
hf.getRight().append(right);
//加入页眉
dataSheet.getSettings().setHeader(hf);
//加入页脚
//dataSheet.getSettings().setFooter(hf);
}
我们可以用如下代码测试该方法:
try {
//创建一个工作薄
WritableWorkbook workbook = Workbook.createWorkbook(new File("D:/test1.xls"));
//待插入的工作表
WritableSheet dataSheet = workbook.createSheet("加入页眉",0);
ExcelUtils.setHeader(dataSheet, "chb", "2007-03-06", "第1页,共3页");
workbook.write();
workbook.close();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
六偷懒工具设计之sql2Excel
今天在公司陪山东客户调试,远程登录,我在linux下什么工具都没有,用ssh登录服务器,直接用mysql查询数据库,提出记录中的所有汉字全是乱码。哎,可恶的公司,不让我用windows,要不我就可以用putty或者EMS了,我ft!
甚是不爽之下,我决定自己写个工具了,把客户数据库中的数据全部提取并保存到Excel中,这样我不就可以一目了然了嘛,嘿嘿,好吧,那我就写一个工具吧。
第一部分就是谁都会的jdbc操作,连接数据库,提取数据集合。
Connection con;
Statement state;
/**初始化连接
* @param serverIp
* @param dataBase
* @param userName
* @param password
* @throws ClassNotFoundException
* @throws SQLException
*/
public void init(String serverIp,String dataBase,String userName,String password) throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
//配置数据源
String url="jdbc:mysql://"+serverIp+"/"+dataBase+"?useUnicode=true&characterEncoding=GB2312";
con=DriverManager.getConnection(url,userName,password);
}
/**得到查询结果集
* @param sql
* @return
* @throws SQLException
*/
public ResultSet getResultSet(String sql) throws SQLException{
state = con.createStatement();
ResultSet res = state.executeQuery(sql);
return res;
}
/**关闭连接
* @throws SQLException
*/
public void close() throws SQLException{
if(con!=null)
con.close();
if(state!=null)
state.close();
}
第二部分就是把ResultSet中的记录写入一个Excel文件
操作Excel,我用的是jxl,不熟的同学可以参考:利用java操作Excel文件
/**将查询结果写入Excel文件中
* @param rs
* @param file
* @throws SQLException
*/
public void writeExcel(ResultSet rs,File file) throws SQLException{
WritableWorkbook wwb = null;
try{
//首先要使用Workbook类的工厂方法创建一个可写入的工作薄(Workbook)对象
wwb = Workbook.createWorkbook(file);
} catch (IOException e){
e.printStackTrace();
}
if(wwb!=null){
WritableSheet ws = wwb.createSheet("sheet1", 0);
int i=0;
while(rs.next()){
Label label1 = new Label(0, i, rs.getString("id"));
Label label2 = new Label(1, i, rs.getString("category"));
try {
ws.addCell(label1);
ws.addCell(label2);
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
i++;
}
try {
//从内存中写入文件中
wwb.write();
//关闭资源,释放内存
wwb.close();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e){
e.printStackTrace();
}
}
}
测试程序:
Sql2Excel se = new Sql2Excel();
try {
se.init("127.0.0.1","mydabase", "root", "1234");
ResultSet rs = se.getResultSet("select id,category from xx ");
se.writeExcel(rs, new File("/root/sql2excel.xls"));
se.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
E. java怎么把xls格式的文件另存为xlsx文件,不能直接改后缀名
那就需要一个同时兼容老版本的xls和新版本的xlsx的库 这样的库可能不太多啊 但应该是可以搜到的
F. java和excel
1:excel表头设置
文件->页面设置->工作表,在“顶端标题行”里选择设置,比如第1行作为表头可以输入$1:$1
2:mysql
获取
表头信息
use
information_schema
select
*
from
columns
where
table_name='表名';
show
columns
from
表名;
G. 怎么用xls文件生成java文件
去学学怎么用POI吧
POI可以到www.apache.org下载到。实际运行时,需要有poi包就可以了。HSSF提供给用户使用的对象在rg.apache.poi.hssf.usermodel包中,主要部分包括Excel对象,样式和格式,还有辅助操作。有以下几种对象:
HSSFWorkbook excel的文档对象
HSSFSheet excel的表单
HSSFRow excel的行
HSSFCell excel的格子单元
HSSFFont excel字体
HSSFDataFormat 日期格式
H. excel往java中导入怎么解决
1、加入依赖的jar文件:
1
2
3
引用:
*mysql的jar文件
*Spring_HOME/lib/poi/*.jar
2、编写数据库链接类
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
package com.zzg.db;
import java.sql.Connection;
import java.sql.DriverManager;
public class DbUtils {
private static Connection conn;
static {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/test","root","123456");
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConn() {
return conn;
}
public static void setConn(Connection conn) {
DbUtils.conn = conn;
}
}
3、编写数据库操作类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.zzg.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class ExcuteData {
private PreparedStatement pstmt;
public boolean ExcuData(String sql) {
Connection conn = DbUtils.getConn();
boolean flag=false;
try {
pstmt = conn.prepareStatement(sql);
flag=pstmt.execute();
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
}
4、编写Excel表格实体类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.zzg.model;
public class TableCell {
private String _name;
private String _value;
public String get_name() {
return _name;
}
public void set_name(String _name) {
this._name = _name;
}
public String get_value() {
return _value;
}
public void set_value(String _value) {
this._value = _value;
}
}
5、编写主键生成方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.zzg.util;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
public class GenericUtil {
public static String getPrimaryKey()
{
String primaryKey;
primaryKey = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
Random r = new Random();
primaryKey +=r.nextInt(100000)+100000;
return primaryKey;
}
}
6、编写Excel操作类
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
package com.zzg.deployData;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.zzg.db.ExcuteData;
import com.zzg.model.TableCell;
import com.zzg.util.GenericUtil;
public class OperExcel<T extends Serializable> {
private HSSFWorkbook workbook;
private String tableName;
private Class<T> type;
private String sheetName;
public OperExcel(File excelFile, String tableName, Class<T> type,
String sheetName) throws FileNotFoundException,
IOException {
workbook = new HSSFWorkbook(new FileInputStream(excelFile));
this.tableName = tableName;
this.type = type;
this.sheetName = sheetName;
InsertData();
}
// 向表中写入数据
public void InsertData() {
System.out.println("yyy");
ExcuteData excuteData = new ExcuteData();
List<List> datas = getDatasInSheet(this.sheetName);
// 向表中添加数据之前先删除表中数据
String strSql = "delete from " + this.tableName;
excuteData.ExcuData(strSql);
// 拼接sql语句
for (int i = 1; i < datas.size(); i++) {
strSql = "insert into " + this.tableName + "(";
List row = datas.get(i);
for (short n = 0; n < row.size(); n++) {
TableCell excel = (TableCell) row.get(n);
if (n != row.size() - 1)
strSql += excel.get_name() + ",";
else
strSql += excel.get_name() + ")";
}
strSql += " values (";
for (short n = 0; n < row.size(); n++) {
TableCell excel = (TableCell) row.get(n);
try {
if (n != row.size() - 1) {
strSql += getTypeChangeValue(excel) + ",";
} else
strSql += getTypeChangeValue(excel) + ")";
} catch (RuntimeException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//执行sql
excuteData.ExcuData(strSql);
}
}
/**
* 获得表中的数据
* @param sheetName 表格索引(EXCEL 是多表文档,所以需要输入表索引号)
* @return 由LIST构成的行和表
*/
public List<List> getDatasInSheet(String sheetName) {
List<List> result = new ArrayList<List>();
// 获得指定的表
HSSFSheet sheet = workbook.getSheet(sheetName);
// 获得数据总行数
int rowCount = sheet.getLastRowNum();
if (rowCount < 1) {
return result;
}
// 逐行读取数据
for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) {
// 获得行对象
HSSFRow row = sheet.getRow(rowIndex);
if (row != null) {
List<TableCell> rowData = new ArrayList<TableCell>();
// 获得本行中单元格的个数
int columnCount = sheet.getRow(0).getLastCellNum();
// 获得本行中各单元格中的数据
for (short columnIndex = 0; columnIndex < columnCount; columnIndex++) {
HSSFCell cell = row.getCell(columnIndex);
// 获得指定单元格中数据
Object cellStr = this.getCellString(cell);
TableCell TableCell = new TableCell();
TableCell.set_name(getCellString(
sheet.getRow(0).getCell(columnIndex)).toString());
TableCell.set_value(cellStr == null ? "" : cellStr
.toString());
rowData.add(TableCell);
}
result.add(rowData);
}
}
return result;
}
/**
* 获得单元格中的内容
*
* @param cell
* @return result
*/
protected Object getCellString(HSSFCell cell) {
Object result = null;
if (cell != null) {
int cellType = cell.getCellType();
switch (cellType) {
case HSSFCell.CELL_TYPE_STRING:
result = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
result = cell.getNumericCellValue();
break;
case HSSFCell.CELL_TYPE_FORMULA:
result = cell.getNumericCellValue();
break;
case HSSFCell.CELL_TYPE_ERROR:
result = null;
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
result = cell.getBooleanCellValue();
break;
case HSSFCell.CELL_TYPE_BLANK:
result = null;
break;
}
}
return result;
}
// 根据类型返回相应的值
@SuppressWarnings("unchecked")
public String getTypeChangeValue(TableCell excelElement)
throws RuntimeException, Exception {
String colName = excelElement.get_name();
String colValue = excelElement.get_value();
String retValue = "";
if (colName.equals("id")) {
retValue = "'" + GenericUtil.getPrimaryKey() + "'";
return retValue;
}
if (colName == null) {
retValue = null;
}
if (colName.equals("class_createuser")) {
retValue = "yaa101";
return "'" + retValue + "'";
}
retValue = "'" + colValue + "'";
return retValue;
}
}
7、编写调用操作Excel类的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.zzg.deployData;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
public class DeployData {
private File fileOut;
public void excute(String filepath) {
fileOut = new File(filepath);
this.deployUserInfoData();
}
public void deployUserInfoData() {
try {
new OperExcel(fileOut, "test", Object.class, "Sheet1");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
8、编写客户端
1
2
3
4
5
6
7
8
9
10
package com.zzg.client;
import com.zzg.deployData.DeployData;
public class DeployClient {
public static void main(String[] args) {
DeployData deployData = new DeployData();
deployData.excute("D://test.xls");
}
}
I. java怎样读写*.xls表的名称
用file去写。懂吗?文件名称是file,内容是jxl.jar可以读的。比如用IO流写到磁盘上,就用FileOutputStream ot = new FileOutputStream("C:\\Users\\xy\\Desktop\\key1.xls");
使用response,那么就在返回头里写入文件的名称格式
J. java xls下载方法
String 文件名 = 文件路径.substring(getWJLJ().lastIndexOf(File.separator)+1);
response.setContentType("appication/pdf");//下载东西的格式
response.setHeader("Content-disposition", "attachment;文件名="+文件名);
try {
FileInputStream fis = new FileInputStream(文件路径);
java.io.OutputStream os = response.getOutputStream();
byte[] b = new byte[1024];
int len = 0;
while((len = fis.read(b))!=-1){
os.write(b, 0, len);
}
os.flush();
os.close();
fis.close();
思路就是,获取文件名字和文件路径,知道文件格式,创建IO进行下载。