读取excel表格内容,处理后写输出xt文件上

参考地址:https://www.cnblogs.com/kingsmart/p/13522565.html

    public class ExcelUtility
    {
        /// <summary>        
        /// 将excel中的数据导入到DataTable中
        /// </summary>
        /// <param name="sheetName">excel工作薄sheet的名称</param>
        /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
        /// <returns></returns>
        public static DataTable  ExcelToDataTable(string sheetName, bool isFirstRowColumn)
        {
            var fileName = "D:/JSTCodeGenerator/Entity.xlsx";
            XSSFWorkbook workbook;
            ISheet sheet = null;
            DataTable data = new DataTable();
            int startRow = 0;
            List<EntityModel> modelList = new List<EntityModel>();

            try
            {
                FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                //if (fileName.IndexOf(".xlsx") > 0) // 2007版本
                workbook = new XSSFWorkbook(fs);
                //else
                //    if (fileName.IndexOf(".xls") > 0) // 2003版本
                //    workbook = new HSSFWorkbook(fs);
                if (sheetName != null)
                {
                    sheet = workbook.GetSheet(sheetName);
                    if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
                    {
                        sheet = workbook.GetSheetAt(0);
                    }
                }
                else
                {
                    sheet = workbook.GetSheetAt(0);
                }
                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(0);
                    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                    if (isFirstRowColumn)
                    {
                        var model = new EntityModel();
                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                        {
                            ICell cell = firstRow.GetCell(i);
                            if (cell != null)
                            {
                                string cellValue = cell.StringCellValue;
                                if (cellValue != null)
                                {
                                    DataColumn column = new DataColumn(cellValue);
                                    data.Columns.Add(column);
                                }

                                switch (i.ToString())
                                {
                                    case "0": model.JsonField = cellValue; break;
                                    case "1": model.Field = cellValue; break;
                                    case "2": model.Title = cellValue; break;
                                    default: break;
                                }
                            }
                        }
                        modelList.Add(model);
                        startRow = sheet.FirstRowNum + 1;
                    }
                    else
                    {
                        startRow = sheet.FirstRowNum;
                    }

                    //最后一列的标号
                    int rowCount = sheet.LastRowNum;
                    for (int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue; //没有数据的行默认是null       

                        DataRow dataRow = data.NewRow();
                        var model = new EntityModel();
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
                            { 
                                var cellValue = row.GetCell(j).ToString();
                                dataRow[j] = cellValue;
                                //AddModel(i, row.GetCell(j).ToString(), modelList);
                                switch (j.ToString())
                                {
                                    case "0": model.JsonField = cellValue; break;
                                    case "1": model.Field = cellValue; break;
                                    case "2": model.Title = cellValue; break;
                                    default: break;
                                }
                            }
                        }
                        modelList.Add(model);

                        data.Rows.Add(dataRow);
                    }
                }
                WriteToFile(modelList, true);
                return data;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// 写道本地文件
        /// </summary>
        /// <param name="modelList"></param>
        public static void WriteToFile(List<EntityModel> modelList, bool formatField = false) {
            try
            {
                //string path = HttpContext.Current.Server.MapPath("~") + 
                string path = "D:/JSTCodeGenerator/" + $"EntityModel{DateTime.Now.ToString("yyyy-MM-ddHHmmssfff")}.txt";
                StringBuilder strBuilder = new StringBuilder();
                for (int i = 0; i < modelList.Count; i++)
                {
                    var model = modelList[i];
                    if (formatField) { 
                        model.Field = ToUpperCamelCase(model.Field);
                    }
                    strBuilder.Append("/// <summary>\n");
                    strBuilder.Append($"/// {model.Title}\n");
                    strBuilder.Append($"/// <summary>\n");
                    strBuilder.Append($"[JsonProperty(\"{model.JsonField}\")]\n");
                    strBuilder.Append($"public string {model.Field} {{ get; set; }}\n");
                    strBuilder.Append($"\n");
                }

                string str = strBuilder.ToString();

                if (!File.Exists(path))
                {
                    FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);

                    StreamWriter sw = new StreamWriter(fs);
                    sw.Write(str);
                    sw.Flush();
                    sw.Close();
                }
                else
                {
                    FileStream fs = new FileStream(path, FileMode.Append);
                    //文本写入
                    StreamWriter sw = new StreamWriter(fs);
                    sw.Write(str);
                    sw.Flush();
                    sw.Close();
                }
            }
            catch(Exception e) {
                Console.WriteLine($"error:{e.Message}, stackTrace:{e.StackTrace}");
            }
            
        }

        public static string ToUpperCamelCase(string inputStr) {
            if (string.IsNullOrEmpty(inputStr))
            {
                return "";
            }
            if (inputStr.IndexOf("_") > -1)
            {
                StringBuilder strBuilder = new StringBuilder();
                string[] inputList = inputStr.Split('_');
                for (int i = 0; i < inputList.Length; i++) {
                    strBuilder.Append(ToUpperFirstLetter(inputList[i]));
                }
                return strBuilder.ToString();
            }
            else {
                return ToUpperFirstLetter(inputStr);
            }
        }
        public static string ToUpperFirstLetter(string inputStr) {
            if (string.IsNullOrEmpty(inputStr)) {
                return "";
            }
            return inputStr.First().ToString().ToUpper() + inputStr.Substring(1);
        }
    }

 

posted @ 2022-04-12 18:31  留下成长的足迹  阅读(51)  评论(0编辑  收藏  举报