javaPoi操作csv xlsx
区别:用JavaPOI导出Excel时,我们会考虑到Excel版本及数据量的问题。针对不同的Excel版本,要采用不同的工具类。 HSSFWorkbook:是操作Excel2003以前(包括2003)的版本,扩展名是.xls; XSSFWorkbook:是操作Excel2007的版本,扩展名是.xlsx; 对于不同版本的EXCEL文档要使用不同的工具类,如果使用错了,会提示如下错误信息。 org.apache.poi.openxml4j.exceptions.InvalidOperationException org.apache.poi.poifs.filesystem.OfficeXmlFileException 从POI 3.8版本开始,提供了一种基于XSSF的低内存占用的API----SXSSF 当数据量超出65536条后,在使用HSSFWorkbook或XSSFWorkbook,程序会报OutOfMemoryError:Javaheap space;内存溢出错误。这时应该用SXSSFworkbook。
读取xlsx内容
package test; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; public class read { public static void main(String[] args) throws IOException { String name= "testa.xlsx"; //创建输入流 InputStream is=new FileInputStream(name); //创建工作簿 XSSFWorkbook hb=new XSSFWorkbook(is); //获取sheet页 XSSFSheet xh=hb.getSheet("xx"); //xh.getLastRowNum() 得到总行数 System.out.println("sheet行数:"+xh.getLastRowNum()); //xh.getRow(0) 获得0行 getCell(0) 0列数据 即第一个单元格 System.out.println(xh.getRow(0).getCell(0)); } }向xlsx写入内容
package test; import org.apache.poi.ss.usermodel.FillPatternType; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.xssf.usermodel.*; import java.io.*; public class write { public static void main(String[] args) throws IOException { //创建一个工作簿 XSSFWorkbook workbook = new XSSFWorkbook(); //创建sheet页 XSSFSheet sheet = workbook.createSheet("test"); //创建工作簿样式 // sheet.setDefaultRowHeight((short)(20 *256)); //设置第一列 第二列 宽度 即你要的宽度 * 256 sheet.setColumnWidth(0,50 * 256); sheet.setColumnWidth(1,20 * 256); //创建XSSFCellStyle 格式 XSSFCellStyle cellStyle = workbook.createCellStyle(); //设置填充背景颜色 cellStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex()); //设置填充模式 cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); //字体样式 创建字体对象XSSFFont XSSFFont xssfFont = workbook.createFont(); xssfFont.setFontName("楷体"); //向单元格设置以上设置的属性 cellStyle.setFont(xssfFont); //以下是正题向文件中写入数据 是向xlsx文件 不是csv(csv是以逗号分隔的) //创建行 XSSFRow row = sheet.createRow(0); row.setHeight((short)(30*20)); //创建单元格 XSSFCell cell = row.createCell(0); XSSFCell cell1 = row.createCell(1); //设置值 cell.setCellValue("hah"); cell1.setCellValue("hello"); cell.setCellStyle(cellStyle); cell1.setCellStyle(cellStyle); //创建输出流 FileOutputStream outputStream = new FileOutputStream("F:\\学习\\test\\write.xlsx"); workbook.write(outputStream); outputStream.flush(); outputStream.close(); System.out.println("写入完成"); } }下面是自己实际运用到的例子
实现内容: javaPoi 利用CsvReader先从csv文件读取数据 再用XSSFWorkbook向xlsx文件写入数据,代码里面设置了单元格属性(居中,字体大小,宽度 ,高度等)及向xlsx写入过程中科学计数法等相关问题解决
package test; import com.csvreader.CsvReader; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.VerticalAlignment; import org.apache.poi.xssf.usermodel.*; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class smallfile { String ALL = "F:\\学习\\test\\wenj\\all_1000.xlsx"; String csv[]={"F:\\学习\\test\\wenj\\ghbb_1000.csv","F:\\学习\\test\\wenj\\bonc_zhfk_1000.CSV"}; //第一行的名称 String [] first_row = {"库名","表名","表属性(内部外部)","文件总数(个)","块总数(个)","文件总大小(单位byte)","文件大小平均值(单位byte)"}; //列的宽度 Integer [] cloumn_width={12,44,26,20,17,30,35}; String [] sheetNames={"GHBB","BONC_ZHFK"}; public static void main(String[] args) throws IOException { String BSS = "F:\\学习\\test\\wenj\\bss_1000.csv"; String BONC_ZHFK = "F:\\学习\\test\\wenj\\bonc_zhfk_1000.CSV"; //创建工作簿 smallfile smallfile = new smallfile(); XSSFWorkbook workbook = new XSSFWorkbook(); XSSFDataFormat dataFormat=workbook.createDataFormat(); XSSFCellStyle cellStyle = smallfile.setCenter(workbook); System.out.println("cellStyle:"+cellStyle.getVerticalAlignmentEnum()); System.out.println("cellStyle:"+cellStyle.getVerticalAlignmentEnum()); //创建sheet页 int sheetIndex=0; for (String sheetName : smallfile.sheetNames) { //创建sheet页 System.out.println("-----创建sheet页--------:"+sheetName); XSSFSheet sheet = smallfile.setSheet(workbook, sheetName); //开始读取数据(csv文件) //创建csv读取对象 CsvReader csvReader = new CsvReader(smallfile.csv[sheetIndex]); //跳过读取表头 boolean headers = csvReader.readHeaders(); //读取的行数 int num = 0; //定义字段类型 String db_name = null; String table_name = null; String tbl_type = null; Object file_nums = null; Object blockcounts = null; Object filesizes = null; Object avg_filesizes = null; while (csvReader.readRecord()) { //创建行 XSSFRow row = sheet.createRow(num); if (csvReader.get(6)!=null && !csvReader.get(5).equals("") && num>0) { db_name = csvReader.get(0); table_name = csvReader.get(1); tbl_type = csvReader.get(2); // System.out.println("num:"+num); file_nums = Double.parseDouble(csvReader.get(3)); blockcounts = Double.parseDouble(csvReader.get(4)); filesizes = Double.parseDouble(csvReader.get(5)); avg_filesizes = Double.parseDouble(csvReader.get(6)); List list = new ArrayList<Object>(); list.add(db_name); list.add(table_name); list.add(tbl_type); list.add(file_nums); list.add(blockcounts); list.add(filesizes); list.add(avg_filesizes); if (list.size() == 7) { //将读取的数据 向all_1000.xlsl文件中写入 for (int i = 0; i < 7; i++) { smallfile.insertCell(row, i, list.get(i),cellStyle,dataFormat); } smallfile.flushDate(workbook); } } else if (num==0){ //num=0时候 for (int i = 0; i < 7; i++) { //插入表头第一行 smallfile.setFirstRow(row,i,num,cellStyle); } smallfile.flushDate(workbook); } num += 1; } sheetIndex++; } } //设置第一行单元格内容 public void setFirstRow(XSSFRow row,int i,int num,CellStyle cellStyle){ //设置高度 row.setHeight((short)(30*20)); XSSFCell cell = row.createCell(i); //设置第一行内容 cell.setCellValue(first_row[i]); cell.setCellStyle(cellStyle); } //设置样式居中 public XSSFCellStyle setCenter(XSSFWorkbook workbook){ XSSFCellStyle cellStyle=workbook.createCellStyle(); //设置垂直居中 // cellStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex()); cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); //设置水平居中 cellStyle.setAlignment(HorizontalAlignment.CENTER); System.out.println(cellStyle.getVerticalAlignmentEnum()+"<>"+cellStyle.getAlignmentEnum()); return cellStyle; } //想单元格插入数据 public void insertCell(XSSFRow row, int i, Object value,CellStyle cellStyle,XSSFDataFormat dataFormat) { XSSFCell rowCell = row.createCell(i); if (i >= 3) { cellStyle.setDataFormat(dataFormat.getFormat("0.00")); String val=""+Double.parseDouble(value.toString()); System.out.println("val:"+val); if (val.matches(".*E.*")){ String [] tmp_n=val.split("E"); System.out.println(tmp_n[0]+"<>"+tmp_n[1]); String jjj=""+Double.parseDouble(tmp_n[0])*Math.pow(10,Double.parseDouble(tmp_n[1])); System.out.println("jjj:"+jjj); } rowCell.setCellValue(Double.parseDouble(value.toString())); System.out.println("i>=3 value:"+Double.parseDouble(value.toString())); //当大于3说明 操作是exel后面4个列 转换为double } else { rowCell.setCellValue(value.toString()); } rowCell.setCellStyle(cellStyle); } //flush数据到工作簿 public void flushDate(XSSFWorkbook workbook) throws IOException { FileOutputStream outputStream = new FileOutputStream(ALL); workbook.write(outputStream); outputStream.flush(); outputStream.close(); } //设置列的宽度 public void setCloumn_width(XSSFSheet sheet){ int i=0; for (Integer integer : cloumn_width) { sheet.setColumnWidth(i, integer * 256); i++; } } //创建sheet页 public XSSFSheet setSheet(XSSFWorkbook workbook,String sheetname){ //创建bss sheet页 XSSFSheet sheet = workbook.createSheet(sheetname); //设置列的宽度 setCloumn_width(sheet); return sheet; } }