JAVA读写EXCELE

来源:互联网 发布:微信mac下载 编辑:程序博客网 时间:2024/06/05 16:17

package com.hr.dao;

import java.io.File;
import java.io.IOException;
import jxl.*;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.read.biff.BiffException;
import jxl.Workbook;
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 JxlAdd {

 public String jxlAdd(File filename, File tofile) throws IOException,
   BiffException, RowsExceededException, WriteException {
  StringBuffer sb = new StringBuffer();
  WritableWorkbook wwb = Workbook.createWorkbook(tofile);
  WritableSheet ws = wwb.createSheet("test", 0);
  WritableFont wf = new WritableFont(WritableFont.TAHOMA, 20,
    WritableFont.BOLD, true, UnderlineStyle.SINGLE,
    jxl.format.Colour.DARK_BLUE);
  // 第一个: TIMES是字体大小(ARIAL字体名称),他写的是18 第二个: BOLD是判断是否为斜体,选择true时为斜体 第三个:
  // UnderlineStyle.NO_UNDERLINE 下划线 第四个: jxl.format.Colour.RED 字体颜色是红色的

  WritableCellFormat wcfF = new WritableCellFormat(wf);
  wcfF.setBackground(Colour.BLUE); // 设置单元格背景色
  Workbook wb = Workbook.getWorkbook(filename);
  Cell[] cell = null;
  // String read=null;
  Double read = null;
  int rowNum = 0;

  if (wb == null)
   return null;
  Sheet[] sheet = wb.getSheets();
  if (sheet != null && sheet.length > 0) {
   for (int i = 0; i < sheet.length; i++) {
    rowNum = sheet[i].getRows();
    for (int j = 0; j < rowNum; j++) {
     cell = sheet[i].getRow(j);
     if (cell != null && cell.length > 0) {
      for (int k = 0; k < cell.length; k++) {
       // System.out.println(rowNum);
       if (cell[k].getContents() != "") {
        read = new Double(cell[k].getContents());//输出数值型
       }
       // System.out.println(cell[k].getContents());//输出字符型
       // Label label = new Label(k, j,read,wcfF);//第四个是可选项,是输入这个label里面的样式
       jxl.write.Number label = new jxl.write.Number(k, j,
         read, wcfF); // 输出数字型格式
       ws.addCell(label);
       sb.append("");// 连接字符串
      }
     }
     sb.append("");
    }
    sb.append("");
   }
  }
  wwb.write();
  try {
   wwb.close();
  } catch (WriteException e) {
   e.printStackTrace();
  }
  wb.close();
  System.out.println("成功");
  return wb.toString();
 }
}
 

 

package com.hr.dao;

import java.io.File;
import java.io.IOException;
import jxl.read.biff.BiffException;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

public class test {
 public static void main(String[] args) {
  JxlAdd jxladd=new JxlAdd();
  File filename=new File("D:/jxltest.xls");
  File tofile=new File("E:/jxltest.xls");
  try {
   jxladd.jxlAdd(filename, tofile);
  } catch (IOException e) {
   e.printStackTrace();
  } catch (RowsExceededException e) {
   e.printStackTrace();
  } catch (BiffException e) {
   e.printStackTrace();
  } catch (WriteException e) {
   e.printStackTrace();
  }
  
 }

}

原创粉丝点击