欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java对xls文件进行读写操作示例代码

程序员文章站 2024-02-22 17:32:52
前言 本文主要给大家介绍的是关于java对xls文件进行读写操作的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍: win7_x64...

前言

本文主要给大家介绍的是关于java对xls文件进行读写操作的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍:

  • win7_x64
  • idea

java读写xls文件,使用库jxl.jar

读写xls文件,这里是在知道表格格式的前提下进行操作的。

目前无法操作xlsx文件

准备工作

将库jxl.jar添加到工程依赖中

java代码示例

示例:从几个文件中读取数据并汇总到一个文件中

表格中的数据规定为:首行为标题,以下是数据和名称;例如

单位名 金额
单位1 948.34
单位2 4324
单位5 324

准备好表格文件,放在指定目录下

示例过程大致为:在指定目录找到所有xls文件;遍历所有文件,读取出所有的单位名称;将单位名称排序;再遍历一次所有文件,将每个文件中单位对应的金额读出并存储;最后写到输出表格中。

final string wsfiledir = "h:/otherworkdocs/ws"; // 原始数据存放的目录
final string resfilepath = "h:/otherworkdocs/output/jan_feb_mar_sum.xls";
rwexcel rwexcel = new rwexcel(); // 操作xls的实例
// 获取所有的名称并排序
treeset<string> nameset = rwexcel.getnameset(wsfiledir);
// 将名称与下标存入map中
hashmap<string, integer> namerowhashmap = rwexcel.getnamerowhashmap(nameset);
file wsdir = new file(wsfiledir); // 源文件目录
file[] sourcefiles = wsdir.listfiles();
// 存储单位名称与金额对应的数据
list<hashmap<string, float>> datalist = new arraylist<>(10);
if (sourcefiles != null) {
 for (file sf : sourcefiles) {
  // 装载数据
  datalist.add(rwexcel.getsourcedata(sf.getabsolutepath()));
 }
}
// 原始数据已经全部读出来,和名称一次性全部写入
rwexcel.writealltoresfile(resfilepath, namerowhashmap, datalist);
// 补充标题栏的标题
if (null != sourcefiles) {
 int col = 1; // 起始列的序号
 for (file f : sourcefiles) {
  string filename = f.getname();
  string name = filename.substring(0, filename.length() - 4);
  rwexcel.updatecontent(resfilepath, name, 0, col);
  col++;
 }
}

java代码

新建一个类rwexcel来操作xls文件。

public class rwexcel {
 /**
  * 存储名称
  */
 private treeset<string> nametreeset = new treeset<>();
 /**
  * 名称以及排列的下标号
  */
 private hashmap<string, integer> namerowmap = new hashmap<>();
 public treeset<string> getnameset(string wspath) {
  try {
   file wsdir = new file(wspath);
   if (wsdir.exists() && wsdir.isdirectory()) {
    println("工作目录存在");
    file[] files = wsdir.listfiles();
    if (files != null && files.length > 0) {
     for (file cfile : files) {
      getnamesfromfile(cfile, this.nametreeset);
     }
    }
   }
  } catch (exception e) {
   e.printstacktrace();
  }
  this.nametreeset.comparator();
  return this.nametreeset;
 }
 /**
  * 将名称set排序后存入hashmap
  * 下标从1开始
  */
 public hashmap<string, integer> getnamerowhashmap(treeset<string> nameset) {
  nameset.comparator();
  int index = 1;
  for (string name : nameset) {
   this.namerowmap.put(name, index);
   index++;
  }
  return this.namerowmap;
 }
 /**
  * 所有数据存入表格
  */
 public void writealltoresfile(string resfilepath, map<string, integer> namemap, list<hashmap<string, float>> datalist) {
  file resfile = new file(resfilepath);
  if (!resfile.exists()) {
   try {
    resfile.createnewfile();
   } catch (ioexception e) {
    e.printstacktrace();
   }
  }
  if (resfile.exists()) {
   try {
    // 先写名称
    writableworkbook wwb = workbook.createworkbook(resfile);
    writablesheet ws = wwb.createsheet("sum", 0);
    label label = new label(0, 0, "单位名称");
    ws.addcell(label);
    for (map.entry<string, integer> entry : namemap.entryset()) {
     label namelabel = new label(0, entry.getvalue(), entry.getkey());
     ws.addcell(namelabel);
     for (int j = 0; j < datalist.size(); j++) {
      number zerocell = new number(j + 1, entry.getvalue(), 0);
      ws.addcell(zerocell);
     }
    }
    for (int datacolumn = 0; datacolumn < datalist.size(); datacolumn++) {
     hashmap<string, float> datamap = datalist.get(datacolumn);
     // 遍历这个map 将所有的数据对应填入
     for (map.entry<string, float> dataentry : datamap.entryset()) {
      int row = namerowmap.get(dataentry.getkey());
      number numbercell = new number(datacolumn + 1, row, dataentry.getvalue());
      ws.addcell(numbercell);
     }
    }
    wwb.write();
    wwb.close();
   } catch (exception e) {
    e.printstacktrace();
   }
  }
 }
 private void getnamesfromfile(file inputfile, treeset<string> hashset) throws ioexception, biffexception {
  workbook workbook;
  inputstream is = new fileinputstream(inputfile);
  workbook = workbook.getworkbook(is);
  sheet sheet0 = workbook.getsheet(0);
  int columnsum = sheet0.getcolumns(); // 总列数
  int rsrows = sheet0.getrows();  // 总行数
  // 从1下标开始
  for (int i = 1; i < rsrows; i++) {
   cell cell = sheet0.getcell(0, i);
   if (!isempty(cell.getcontents())) {
    hashset.add(cell.getcontents());
   }
  }
  println("此文件行数减一 = " + (rsrows - 1) + " , 当前获取到的所有单位数 " + hashset.size());
 }
 /**
  * 从原始数据中读取并匹配的存入结果文件中
  */
 private hashmap<string, float> getsourcedata(string source) {
  file sfile = new file(source);
  if (!sfile.exists()) {
   system.out.println("原始文件不存在 复制失败!");
   return null;
  }
  // 读取源文件中的所有数据 <单位名称, 数值>
  hashmap<string, float> sourcehashmap = new hashmap<>();
  try {
   workbook sourcews = workbook.getworkbook(sfile);
   sheet ssheet0 = sourcews.getsheet(0);
   int stotalrows = ssheet0.getrows();  // 总行数
   for (int i = 1; i < stotalrows; i++) {
    cell cellkey = ssheet0.getcell(0, i);
    cell cellvalue = ssheet0.getcell(1, i);
    if (!isempty(cellkey.getcontents()) && !isempty(cellvalue.getcontents())) {
     sourcehashmap.put(cellkey.getcontents(), float.valueof(cellvalue.getcontents()));
    }
   }
   println(source + " 读取到的数据数量 = " + sourcehashmap.size());
  } catch (exception e) {
   e.printstacktrace();
  }
  return sourcehashmap;
 }
 public void updatecontent(string filepath, string input, int row, int column) {
  file file = new file(filepath);
  if (!file.exists()) {
   system.out.println(filepath + " does not exist!");
   return;
  }
  try {
   workbook sourcewb = workbook.getworkbook(file);
   writableworkbook wwb = workbook.createworkbook(file, sourcewb);
   writablesheet wsheet0 = wwb.getsheet(0);
   label label = new label(column, row, input);
   wsheet0.addcell(label);
   wwb.write();
   wwb.close();
  } catch (exception e) {
   e.printstacktrace();
  }
 }
 public rwexcel() {
 }
 private static boolean isempty(string str) {
  if (null == str) {
   return true;
  }
  return str.isempty();
 }
 private static void println(string in) {
  system.out.println(in);
 }
}

示例运行结果

得到以下结果(示例)

单位名称 1月总金额 2月总金额 3月总金额
单位1 0 59.29999924 948.3400269
单位10 0 0 494.2000122
单位11 0 0 11.19999981
单位12 0 0 1.25
单位15 49.36000061 0 0
单位2 0 0 4324
单位24 0 34 0
单位5 0 23123 324
单位6 0 161.2599945 0

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。