当前位置: 首页 > news >正文

4.文件管理(文本、日志、Excel表)

目录

1.文本

2.日志

3.Excel表


1.文本

using System.Text;namespace (自己创建的一个类)
{/// <summary>/// 配置文件*.ini读写器。/// </summary>public class IniFile{[System.Runtime.InteropServices.DllImport("kernel32")]private static extern long WritePrivateProfileString(string section, string key, string value, string file);[System.Runtime.InteropServices.DllImport("kernel32")]private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder value, int size, string file);private string _File;private int _Size = 255;/// <summary>/// 值的最大长度,不能小于0。/// </summary>public int Size{get{return _Size;}set{if (value >= 0){_Size = value;}}}/// <summary>/// 构造函数,值的最大长度默认为255。/// </summary>/// <param name="file">配置文件。</param>public IniFile(string file){_File = file;}/// <summary>/// 构造函数。/// </summary>/// <param name="file">配置文件。</param>/// <param name="size">值的最大长度。</param>public IniFile(string file, int size){_File = file;Size = size; }/// <summary>/// 写配置文件。/// </summary>/// <param name="section">条目。</param>/// <param name="key">键。</param>/// <param name="value">值。</param>public void Write(string section, string key, string value){WritePrivateProfileString(section, key, value, _File);}/// <summary>/// 读配置文件,读取失败返回""。/// </summary>/// <param name="section">条目。</param>/// <param name="key">键。</param>/// <returns>值。</returns>public string Read(string section, string key){StringBuilder value = new StringBuilder(Size);GetPrivateProfileString(section, key, "", value, Size, _File);return value.ToString();}}
}

2.日志

using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace (自己创建的项目)
{class LogHelper{public static ILog logError = LogManager.GetLogger("ErrorLog");public static ILog logInfor = LogManager.GetLogger("InforLog");/// <summary>/// 写入异常信息日志/// </summary>/// <param name="info">异常内容</param>/// <param name="ex">异常</param>public static void WriteLog(string info, Exception ex){if (logError.IsErrorEnabled){logError.Error(info, ex);}}/// <summary>/// 记录普通信息日志/// </summary>/// <param name="info">信息</param>public static void WriteLog(string info){if (logInfor.IsErrorEnabled){logInfor.Error(info);}}}
}

3.Excel表

using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aspose.Cells;namespace (自己创建的项目).文件管理
{class ExcelHelper{#region 新建Excel/// <summary>/// 创建excel/// </summary>/// <param name="path">excel路径</param>/// <param name="colHeader">表头</param>public static void Create(string path, string[] colHeader){Workbook wk = new Workbook();Worksheet ws = wk.Worksheets[0];//Worksheet ws = wk.Worksheets.Add("name");Cells cell = ws.Cells;//Aspose.Cells.Style style = wk.CreateStyle();//style.Font.Name = "微软雅黑";//style.Font.Size = 10;for (int i = 0; i < colHeader.Length; i++){cell[0, i].PutValue(colHeader[i]);}ws.AutoFitColumns();wk.Save(path);GC.Collect();}#endregion#region 新建表/// <summary>/// 添加一张表/// </summary>/// <param name="path">文件路径</param>public static void AddSheet(string path){//实例化工作簿对象Workbook workbook = new Workbook(path);//添加工作表workbook.Worksheets.Add();//workbook.Worksheets.Add("name");//保存workbook.Save(path);//释放资源GC.Collect();}#endregion#region 写入数据/// <summary>/// 写入excel/// </summary>/// <param name="path">excel路径</param>/// <param name="rowdatas">一行数据</param>public static void Write(string path, string[] rowdatas){try{Workbook wk = new Workbook(path);Worksheet ws = wk.Worksheets[0];Cells cell = ws.Cells;//Aspose.Cells.Style style = wk.CreateStyle();//style.Font.Name = "楷体";//style.Font.Size = 12;//style.Font.Color = Color.Red;int rowIndex = cell.MaxRow;for (int i = 0; i < rowdatas.Length; i++){cell[rowIndex + 1, i].PutValue(rowdatas[i]);//cell[rowIndex + 1, i].SetStyle(style);}ws.AutoFitColumns();wk.Save(path);GC.Collect();}catch (Exception){throw;}}public static void Write(string path, string[] rowdatas, string fontName, int fontSize, Color fontColor){try{Workbook wk = new Workbook(path);Worksheet ws = wk.Worksheets[0];Cells cell = ws.Cells;Aspose.Cells.Style style = wk.CreateStyle();style.Font.Name = fontName;style.Font.Size = fontSize;style.Font.Color = fontColor;int rowIndex = cell.MaxRow;for (int i = 0; i < rowdatas.Length; i++){cell[rowIndex + 1, i].PutValue(rowdatas[i]);cell[rowIndex + 1, i].SetStyle(style);}ws.AutoFitColumns();wk.Save(path);GC.Collect();}catch (Exception){throw;}}#endregion#region 读取数据/// <summary>/// 读取数据/// </summary>/// <param name="path">文件路径</param>/// <returns>返回数据表</returns>public static DataTable Read(string path){DataTable dt = new DataTable();try{//打开当前excelWorkbook workbook = new Workbook(path);//打开当前工作表Worksheet worksheet = workbook.Worksheets[0];//获取所有单元格Cells cell = worksheet.Cells;//获取使用的行数int usedRows = cell.MaxRow;int cols = cell.MaxColumn;//读数据if (usedRows > 0){for (int i = 0; i <= usedRows; i++){if (i == 0){for (int j = 0; j <= cols; j++){string val = cell.GetCell(i, j).Value.ToString();DataColumn col = new DataColumn(val);dt.Columns.Add(col);}}else{DataRow dr = dt.NewRow();for (int j = 0; j <= cols; j++){string val = cell.GetCell(i, j).Value.ToString();dr[j] = val;}dt.Rows.Add(dr);}}}//列宽自适应worksheet.AutoFitColumns();//保存workbook.Save(path);//释放资源GC.Collect();}catch (Exception){throw;}return dt;}/// <summary>/// 读取一行数据/// </summary>/// <param name="path">文件路径</param>/// <param name="rowindex">行号从0开始</param>/// <returns>返回数据</returns>public static string[] Read(string path, int rowindex){string[] rowsValue;try{//打开当前excelWorkbook workbook = new Workbook(path);//打开当前工作表Worksheet worksheet = workbook.Worksheets[0];//获取所有单元格Cells cell = worksheet.Cells;//获取使用的行数int usedRows = cell.MaxRow;int cols = cell.MaxColumn;rowsValue = new string[cols+1];//读数据if (usedRows > 0){if (rowindex <= usedRows){for (int i = 0; i <= cols; i++){rowsValue[i] = cell.GetCell(rowindex, i).Value.ToString();}}}//列宽自适应worksheet.AutoFitColumns();//保存workbook.Save(path);//释放资源GC.Collect();}catch (Exception){throw;}return rowsValue;}#endregion#region 获取已使用行数/// <summary>/// 获取已使用的行数/// </summary>/// <param name="path">文件路径</param>/// <returns>行数从0开始</returns>public static int UsedRows(string path){int usedRows = 0;try{//打开当前excelWorkbook workbook = new Workbook(path);//打开当前工作表Worksheet worksheet = workbook.Worksheets[0];//获取所有单元格Cells cell = worksheet.Cells;//获取使用的行数usedRows = cell.MaxRow;//释放资源GC.Collect();}catch (Exception){throw;}return usedRows;}#endregion#region 将DataGridView数据保存到DataTable/// <summary>/// 绑定DataGridView数据到DataTable/// </summary>/// <param name="dgv">复制数据的DataGridView</param>/// <returns>返回的绑定数据后的DataTable</returns>public static DataTable GetDgvToTable(System.Windows.Forms.DataGridView dgv){DataTable dt = new DataTable();// 列强制转换for (int count = 0; count < dgv.Columns.Count; count++){DataColumn dc = new DataColumn(dgv.Columns[count].Name.ToString());dt.Columns.Add(dc);}// 循环行for (int count = 0; count < dgv.Rows.Count; count++){DataRow dr = dt.NewRow();for (int countsub = 0; countsub < dgv.Columns.Count; countsub++){dr[countsub] = Convert.ToString(dgv.Rows[count].Cells[countsub].Value);}dt.Rows.Add(dr);}return dt;}#endregion#region 将datatable数据保存到excel/// <summary>/// DataTable保存到Excel/// </summary>/// <param name="data">数据</param>/// <param name="filepath">保存路径</param>public static void DataTableExport(DataTable data, string filepath){try{Workbook book = new Workbook(); //创建工作簿Worksheet sheet = book.Worksheets[0]; //创建工作表Cells cells = sheet.Cells; //单元格//创建样式Aspose.Cells.Style style = book.CreateStyle();//style.Borders[Aspose.Cells.BorderType.LeftBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //应用边界线 左边界线  //style.Borders[Aspose.Cells.BorderType.RightBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //应用边界线 右边界线  //style.Borders[Aspose.Cells.BorderType.TopBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //应用边界线 上边界线  //style.Borders[Aspose.Cells.BorderType.BottomBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //应用边界线 下边界线   style.HorizontalAlignment = TextAlignmentType.Center; //单元格内容的水平对齐方式文字居中style.Font.Name = "宋体"; //字体style.Font.IsBold = true; //设置粗体style.Font.Size = 11; //设置字体大小//style.ForegroundColor = System.Drawing.Color.FromArgb(153, 204, 0); //背景色//style.Pattern = Aspose.Cells.BackgroundType.Solid; //背景样式//style.IsTextWrapped = true; //单元格内容自动换行//表格填充数据int Colnum = data.Columns.Count;//表格列数 int Rownum = data.Rows.Count;//表格行数 //生成行 列名行 for (int i = 0; i < Colnum; i++){cells[0, i].PutValue(data.Columns[i].ColumnName); //添加表头cells[0, i].SetStyle(style); //添加样式//cells.SetColumnWidth(i, data.Columns[i].ColumnName.Length * 2 + 1.5); //自定义列宽//cells.SetRowHeight(0, 30); //自定义高}//生成数据行 for (int i = 0; i < Rownum; i++){for (int k = 0; k < Colnum; k++){cells[1 + i, k].PutValue(data.Rows[i][k].ToString()); //添加数据cells[1 + i, k].SetStyle(style); //添加样式}//cells[1 + i, 5].Formula = "=B" + (2 + i) + "+C" + (2 + i);//给单元格设置计算公式,计算班级总人数}sheet.AutoFitColumns(); //自适应宽book.Save(filepath); //保存GC.Collect();}catch (Exception e){throw e;}}#endregion}
}

相关文章:

  • 技术干货 | DAC静态参数计算全解析:从偏移误差到总未调整误差
  • 【Go语言基础】对齐边界与内存填充
  • davinci本地启动
  • Network Manager客户端制作小结
  • http2与websocket关系
  • NY339NY341美光固态闪存NW841NW843
  • RAG 升级之路:如何让问答机器人真正“智能”起来
  • 【网工】华为配置专题进阶篇④
  • 合并两个有序链表C++
  • Unity3D仿星露谷物语开发67之创建新的NPC
  • 变幻莫测:CoreData 中 Transformable 类型面面俱到(五)
  • 学习笔记丨AR≠VR:透视沉浸式技术的“虚实象限”法则
  • 【Golang面试题】Go语言实现请求频率限制
  • 记录:注册k8s cluster账号
  • NumPy玩转数据科学
  • Apollo:配置中心使用与介绍
  • C++11 Thread-Local Storage:从入门到精通
  • dify本地部署及添加ollama模型(ubuntu24.04)
  • Docker环境部署
  • Javaweb - 2 HTML
  • 灵璧做网站/今日热榜官网
  • 企业网站的缺点/搜狗搜索推广
  • 做a小视频网站/短信广告投放
  • 济南制作网站的公司吗/今天最火的新闻头条
  • 全新网站开发/营销策划书
  • 保定哪里有做网站的/百度最新秒收录方法2023