添加所需的依赖
1 2 3 4 5
| <dependency> <groupId>com.belerweb</groupId> <artifactId>pinyin4j</artifactId> <version>2.5.1</version> </dependency>
|
创建一个方法来,转换拼音
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public static String getPinYinHeadChar(String str) { if (isNull(str)) { return ""; } String convert = ""; for (int j = 0; j < str.length(); j++) { char word = str.charAt(j); String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word); if (pinyinArray != null) { convert += pinyinArray[0].charAt(0); } else { convert += word; } }
convert = string2AllTrim(convert); return convert.toLowerCase(); }
|
其中PinyinHelper的方法能将汉字字符串转换成首字母拼音的字符串数组
main方法
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
| public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); String s = PingYinUtil.getPinYinHeadChar("支付宝"); System.out.println(s);
List<String> str = new ArrayList<>(); List<String> pin = new ArrayList<>(); List<String> level = new ArrayList<>(); String fileName = "D:\\bin\\桌面\\h_fever_outpatient_org_info.xlsx"; try { XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new FileInputStream(fileName)); int sheetNum = xssfWorkbook.getNumberOfSheets(); System.out.println("该excel文件中总共有:"+sheetNum+"个sheet"); List<Grade> grades = new ArrayList<>(); for(int i = 0;i<sheetNum;i++) { System.out.println("读取第"+(i+1)+"个sheet"); XSSFSheet sheet = xssfWorkbook.getSheetAt(i); int maxRow = sheet.getLastRowNum(); for (int row = 0; row <= maxRow; row++) { int maxRol = sheet.getRow(row).getLastCellNum(); String a = sheet.getRow(row).getCell(0).toString(); str.add(a); pin.add(PingYinUtil.getPinYinHeadChar(a)); level.add(sheet.getRow(row).getCell(2).toString()); } }
try ( SXSSFWorkbook workbook = new SXSSFWorkbook()) { SXSSFSheet sheet = workbook.createSheet();
for(int i=0;i<str.size();i++){ SXSSFRow row = sheet.createRow(i); row.createCell(0).setCellValue(str.get(i)); row.createCell(1).setCellValue(pin.get(i)); row.createCell(2).setCellValue(level.get(i)); }
workbook.setSheetName(0,"sheet");
FileOutputStream out = new FileOutputStream("D:\\bin\\桌面\\" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()).toString() +".xlsx"); workbook.write(out); out.close(); }
} catch (IOException e) { e.printStackTrace(); } }
|