1.Nuget安装NPOI及Pinyin4net
2.Demo 代码部分
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using System.IO;
using System.Text.RegularExpressions;
using NPOI.Util;
using NPOI.SS.Util;
using NPOI.HSSF.Util;
using Pinyin4net.Format;
using Pinyin4net;namespace ConsoleApp5
{class Program{static void Main(string[] args){// 使用示例string input = "中国";string pinyin = ConvertToPinyin(input);pinyin = ConvertToPinyin("升温");pinyin = ConvertToPinyin("降温");Console.WriteLine(pinyin); // 输出: "zhong guo"Console.ReadKey();}// 汉字转拼音public static string ConvertToPinyin(string input){// 创建一个工作簿IWorkbook workbook = new HSSFWorkbook();// 创建一个工作表ISheet sheet = workbook.CreateSheet("Sheet1");// 创建一行IRow row = sheet.CreateRow(0);// 创建一个单元格ICell cell = row.CreateCell(0);// 将汉字写入单元格cell.SetCellValue(input);// 设置单元格格式为文本IDataFormat format = workbook.CreateDataFormat();cell.CellStyle.DataFormat = format.GetFormat("@");// 获取单元格的值string value = cell.StringCellValue;// 创建一个汉语拼音输出格式实例HanyuPinyinOutputFormat pinyinFormat = new HanyuPinyinOutputFormat();pinyinFormat.ToneType = HanyuPinyinToneType.WITHOUT_TONE;// 将汉字转换为拼音string[] results = new string[value.Length];for (int i = 0; i < value.Length; i++){// 获取汉字的拼音string[] pinyinArray = PinyinHelper.ToHanyuPinyinStringArray(value[i], pinyinFormat);// 创建一个汉语拼音输出格式实例,指定不带声调//HanyuPinyinOutputFormat pinyinFormat = new HanyuPinyinOutputFormat();//pinyinFormat.ToneType = HanyuPinyinToneType.WITHOUT_TONE;// 将汉字转换为拼音//string[] pinyinArray = PinyinHelper.ToHanyuPinyinStringArray('中', pinyinFormat);// 如果这个字符不是汉字,则直接使用它的原始值if (pinyinArray == null || pinyinArray.Length == 0){results[i] = value[i].ToString();}else{// 将拼音连接起来results[i] = string.Join(" ", pinyinArray);}}// 关闭工作簿workbook.Close();// 将所有拼音连接起来string pinyin = string.Join(" ", results);return pinyin;}}
}
3.输出部分