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

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}
}

http://www.xdnf.cn/news/14532.html

相关文章:

  • 基于PyQt5和PaddleSpeech的中文语音识别系统设计与实现(Python)
  • Spring Boot + MyBatis + Vue:全栈开发中的最佳实践
  • C++11 右值引用(Rvalue Reference)
  • MySQL 数据库索引详解
  • 【AI时代速通QT】第二节:Qt SDK 的目录介绍和第一个Qt Creator项目
  • Linux tail 命令
  • Android图形系统框架解析
  • 实时输出subprocess.Popen运行程序的日志
  • 面试第三期
  • 【Bug:docker】--Docker同时部署Dify和RAGFlow出现错误
  • Spring-创建第一个SpringBoot项目
  • StableDiffusion实战-手机壁纸制作 第一篇:从零基础到生成艺术品的第一步!
  • 解密提示词工程师:AI 时代的新兴职业
  • 视频续播功能实现 - 断点续看从前端到 Spring Boot 后端
  • C#最佳实践:为何优先使用查询语法而非循环
  • HALCON相机标定
  • Laravel框架的发展前景与Composer的核心作用-优雅草卓伊凡
  • 微信小程序:实现左侧菜单、右侧内容、表单、新增按钮等组件封装
  • 蜻蜓Q系统的技术演进:从Laravel 6到Laravel 8的升级之路-优雅草卓伊凡
  • web3 浏览器注入 (如 MetaMask)
  • 如何获取 vscode 的 vsix 离线插件安装包
  • jmeter学习
  • JETBRAINS IDE 开发环境自定义设置快捷键
  • MySQL存储引擎深度解析:InnoDB、MyISAM、MEMORY 与 ARCHIVE 的全面对比与选型建议
  • FPGA基础 -- Verilog行为级建模之alawys语句
  • 【深度学习】卷积神经网络(CNN):计算机视觉的革命性引擎
  • 最新期刊影响因子,基本包含全部期刊
  • OpenStack入门体验
  • Oracle 详细解析及与 MySQL 的核心区别
  • AI时代的质量显得更为重要