话不多说 , 请看代码:
Excelutil.java
pacote pers.kangxu.datautils.utils; importar java.io.file; importar java.io.fileInputStream; importar java.io.fileOutputStream; importar java.io.ioexception; importar java.io.InputStream; import.UtAil.MaRayList; java.util.list; importar java.util.map; importar org.apache.poi.hssf.usermodel.hssfcellstyle; import org.apache.poi.hssf.usermodel.hsffont; import org.apache.poi.hsssssssssssssssssssssssssssssssssSsSsSsSsSsSsSsSsssssSsssssssssssssssssssssssssssssf.ermodel.hssfont; imported.apache.poi. org.apache.poi.ss.usermodel.cell; importar org.apache.poi.ss.usermodel.cellstyle; importar org.apache.poi.ss.usermodel.cellvalue; import org.apache.poi.ss.s.s.somodel.font; importache; org.apache.poi.ss.usermodel.row; importar org.apache.poi.ss.usermodel.sheet; importar org.apache.poi.ss.usermodel.workbook; omorg.apache.poi.s.util.cellRangeDressres; ExcelUtil { /** * 导出 excel * @param filePath 文件全路径 * @param sheetName sheet页名称 * @param sheetIndex 当前sheet下表 从0开始 * @param fileHeader 头部 * @param datas 内容 */ public static void writeExcel(String filePath,String sheetName, int sheetIndex, String[] fileHeader, List<String[]> datas){ // 创建工作簿 Workbook wb = novo hssfworkbook (); // 创建工作表 folha S = wb.createSheet (); WB.SetSheetName (SheetIndex, SheetName); Linha r = s.Crearrow (0); Célula c = nulo; Fonte Fonte = NULL; CellStyle StyleHeader = NULL; CellStyle styleContent = null; // 粗体 font = wb.createFont (); font.setBoldweight (hssffont.Boldweight_bold); // 设置头样式 styleheader = wb.createCellStyle (); styleheader.setFont (fonte); styleheader.setBorderBottom (hssfcellstyle.border_thin); // 下边框 styleheader.setborderleft (hssfcellstyle.border_thin); // 左边框 styleheader.setbordertop (hssfcellstyle.border_thin); // 上边框 styleheader.setborderright (hssfellstyle.border_thin); // 右边框 右边框 右边框 右边框 上边框 上边框 右边框 上边框 右边框 右边框 右边框 上边框 上边框 上边框 上边框 上边框 上边框 上边框 上边框 上边框 上边框 右边框 上边框 上边框 上边框 上边框 上边框 上边框 上边框 上边框 上边框 上边框 上边框 上边框 上边框eheader.setborderright (hssfellstyle.border_thin); wb.createCellStyle (); stylecontent.setBorderBottom (hssfcellstyle.border_thin); // 下边框 stylecontent.setBorderleft (hssfcellstyle.border_thin); // 左边框 stylecontent.setbordertop (hssfcellstyle.border_thin); // 上边框 stycontent.setdordersright (hsfcellstyl); i = 0; i <fileHeader.length;) {c = r.createCell (i); C.setCellStyle (StyleHeader); c.setCellValue (FileHeader [i]); i ++; } // 设置内容 para (int rownum = 0; rownum <datas.size ();) {// 行 line datas.size () r = s.Createrow (rownum+1); // 创建行 para (int Cellnum = 0; Cellnum <FileHeader.Length;) {C = R.CreateCell (Cellnum); c.setCellValue (DataS.get (ROWNUM) [Cellnum]); C.setCellStyle (StyleContent); Cellnum ++; } rownum ++; } FileOutputStream out = null; tente {// 创建文件或者文件夹, 将内容写进去 if (fileutil.createfile (novo arquivo (filepath))) {out = new FileOutputStream (filepath); wb.Write (Out); }} catch (Exceção e) {e.printStackTrace (); } finalmente {tente {// 关闭流 if (out! = null) {out.flush (); out.Close (); }} catch (ioexception e) {e.printStackTrace (); }}} / ** * 读取 Excel 文件内容 * @param filepath * @param SheetIndex * / public static list <map <string, string >> readExcel (string filepath, int sheetIndex) {list <p map <string, string >> mapList = new ArrayList <pap <pp, string >> (); // 头 List <String> List = new ArrayList <String> (); // int cnt = 0; int idx = 0; tente {inputStream input = new FileInputStream (filepath); // 建立输入流 pasta de trabalho wb = null; wb = novo HSSFWorkbook (entrada); // 获取 folha 页 folha de folha = wb.getSheetat (SheetIndex); Iterator <wrow> linhas = chaphe.rowiterator (); while (linhas.hasnext ()) {linha linha = linhas.next (); Iterador <cell> células = row.celiterator (); Mapa <string, string> map = new hashmap <string, string> (); if (cnt == 0) {// 将头放进 lista 中 while (celular.hasnext ()) {célula = célula.next (); if (isContainMergeCell (Sheet)) {cancelMergeCell (Sheet); } list.add (getStringCellValue (célula)); } cnt ++; continuar; } else {while (Cells.hasNext ()) {Cell Cell = Cells.Next (); if (isContainMergeCell (Sheet)) {cancelMergeCell (Sheet); } // 区别相同的头 list = listutil.ChangesameVal (list); map.put (list.get (idx ++), getStringCellValue (célula)); }} idx = 0; MapList.add (mapa); } retornar mapList; } catch (ioexception ex) {ex.printStackTrace (); } retornar nulo; } / ** * 合并单元格 * @param folha 当前 folha 页 * @param Firstrow 开始行 * @param lastrow 结束行 * @param FirstCol 开始列 * @param lastcol 结束列 * / public static int MerGecell (folha, folha, intstrow, int lastrow, int Firstcol, int lastcol) (folha () } Return Sheet.addmergedRegion (new CellrangeAdRest (Firstrow, Lastrow, FirstCol, LastCol)); } / ** * 取消合并单元格 * @Param Sheet * @param idx * / public static void cancelMerGecell (folha) {int chapheMerGecount = Sheet.getnummergedRegions (); for (int idx = 0; idx <SheetMergeCount;) {CellRangeAddress range = Sheet.getMergedRegion (IDX); String val = getMerGecellValue (Sheet, range.getfirstrow (), range.getLastrow ()); // 取消合并单元格 Sheet.RemoVemergedRegion (IDX); para (int ROWNUM = range.getfirstrow (); rownum <range.getLastrow ()+1;) {for (int Cellnum = range.getfirstcolumn (); Cellnum <range.getLastColumn ()+1;) {sheetrow (ROWNUM) .getCell (Cellnum). Cellnum ++; } rownum ++; } idx ++; }} / ** * 判断指定单元格是否是合并单元格 * @param folha 当前 folha 页 * @param firstrow 开始行 * @param lastrow 结束行 * @param FirstCol 开始列 * @param lastcol 结束列 * @return * / public estático for (int i = 0; i <SheetMergeCount;) {CellRangeAddress range = Sheet.getMergedRegion (i); int primeiroColumn = range.getfirstcolumn (); int lastColumn = range.getLastColumn (); int firstrow = range.getfirstrow (); int lastrow = range.getLastrow (); if (linha> = firstrow && line <= lastrow) {if (colun> = FirstColumn && colun <= lastColumn) {return true; }} i ++; } retornar false; } / ** * 判断 folha 页中是否含有合并单元格 * @param folha * @return * / public static boolean isContainMerGecell (folha) {if (sheet == null) {return false; } Return Sheet.getnummergedRegions ()> 0? Verdadeiro: falso; } / ** * 获取指定合并单元的值 * @Param Sheet * @param linha * @param coluna * @return * / public static string getMergeCellValue (folha, folha, int linha, int coluna) {int sheetMerGecount = Sheet.getNummergedRegions (); for (int i = 0; i <SheetMergeCount;) {CellRangeAddress range = Sheet.getMergedRegion (i); int primeiroColumn = range.getfirstcolumn (); int lastColumn = range.getLastColumn (); int firstrow = range.getfirstrow (); int lastrow = range.getLastrow (); if (linha> = firstrow && line <= lastrow) {if (colun> = FirstColumn && colun <= lastColumn) {linha frut = sheet.getRow (firstrow); Célula fcell = Frow.getCell (FirstColumn); retorno getStringCellValue (fcell); }} i ++; } retornar nulo; } / ** * 获取单元格的值 * @param Cell * @return * / public static string getStringCellValue (célula) {string strcell = ""; if (célula == null) retorna strcell; switch (Cell.getCellType ()) {case Cell.Cell_Type_String: strCell = Cell.GetRichStringCellValue (). GetString (). TRIM (); quebrar; case celular.cell_type_numeric: strcell = string.valueof (Cell.getNumericCellValue ()); quebrar; CELL.CELL_TYPE_BOOLEAN: strcell = string.valueof (Cell.getBooleAnCellValue ()); quebrar; case celular.cell_type_formula: formulaEvaluator avaliador = Cell.getSheet (). avaliador.EvaluateFormulacell (célula); CellValue CellValue = avaliador.Evaluate (célula); strCell = string.valueof (CellValue.getNumberValue ()); quebrar; padrão: strcell = ""; } retornar strcell; }}调用方式如下
ExcelutilTester.java
pacote pers.kangxu.datautils.test; importar java.util.ArrayList; importar java.util.list; importar pers.kangxu.datautils.utils.excelutil; public classe ExcelutilTester {public static void main (string [] args) (list] (string]; dados.add (new String [] {"狗熊", "母", "250"}); dados.add (new String [] {"猪粮", "不明", "251"}); //Excelutil.writeexcel("c://users//administrator//desktop//test//test//test.xls","sheet1",0, new String [] {"姓名", "年龄", "性别"}, dados); System.out.println (Excelutil.readExcel ("c: //users//administrator//desktop//test//test//test.xls", 0)); }}以上就是本文的全部内容 , 希望本文的内容对大家的学习或者工作能带来一定的帮助 , 同时也希望多多支持武林网!