• 读取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);
            }
        }
  • 相关阅读:
    【转】编写高质量代码改善C#程序的157个建议——建议147:重构多个相关属性为一个类
    【转】编写高质量代码改善C#程序的157个建议——建议146:只对外公布必要的操作
    【转】编写高质量代码改善C#程序的157个建议——建议145:避免过长的方法和过长的类
    【转】编写高质量代码改善C#程序的157个建议——建议144:一个方法只做一件事
    【转】编写高质量代码改善C#程序的157个建议——建议143:方法抽象级别应在同一层次
    【转】编写高质量代码改善C#程序的157个建议——建议142:总是提供有意义的命名
    【转】编写高质量代码改善C#程序的157个建议——建议141:不知道该不该用大括号时,就用
    【转】编写高质量代码改善C#程序的157个建议——建议140:使用默认的访问修饰符
    【转】编写高质量代码改善C#程序的157个建议——建议139:事件处理器命名采用组合方式
    SpringMVC学习总结(六)——SpringMVC文件上传例子(2)
  • 原文地址:https://www.cnblogs.com/kingsmart/p/16136426.html
Copyright © 2020-2023  润新知