c#文件操作xml、ini、txt、excel、csv操作全解

来源:互联网 发布:python 读取 csv 编辑:程序博客网 时间:2024/05/18 15:53
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Security.Cryptography;using System.IO;using System.Xml;using System.Data;using System.Runtime.InteropServices;using System.Windows.Forms;namespace util{    public class filedeal    {        [DllImport("kernel32")]        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);        [DllImport("kernel32")]        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);        /// <summary>        /// 读取ini        /// </summary>        /// <param name="group">数据分组</param>        /// <param name="key">关键字</param>        /// <param name="filepath">init文件地址</param>        /// <returns>关键字对应的值,没有时含有默认值</returns>        public static string readini(string group,string key,string filepath){            StringBuilder temp = new StringBuilder();            GetPrivateProfileString(group,key, "", temp, 255, filepath);            return temp.ToString();        }        /// <summary>        /// 存储ini        /// </summary>        /// <param name="group">数据分组</param>        /// <param name="key">关键字</param>        /// <param name="value">关键字对应的值</param>        /// <param name="filepath">ini文件地址</param>        public static void writeini(string group,string key,string value,string filepath)        {            WritePrivateProfileString(group, key, value, filepath);        }        //读取txt成字符串        public static string readtxt(string path)        {            StreamReader sr = new StreamReader(path, Encoding.Default);            string line;            StringBuilder sb = new StringBuilder();            while ((line = sr.ReadLine()) != null)            {                sb.Append(line);            }            return sb.ToString();        }        //读取txt成字符串列表        public static List<string> readtxt(string path)        {            List<string> allstr = new List<string>();            StreamReader sr = new StreamReader(path, Encoding.Default);            string line;            while ((line = sr.ReadLine()) != null)            {                allstr.Add(line);            }            return allstr;        }        //写入txt字符串        public static void writetxt(string path, string content)        {            FileStream fs = new FileStream(path, FileMode.Create);            StreamWriter sw = new StreamWriter(fs);            //开始写入            sw.Flush();            //关闭流            sw.Close();            fs.Close();        }        //导出到execl,需要导入Microsoft.Office.Interop.Excel        public static void ListToExcel(List<String> strarray,string name,string path)        {            System.Data.DataTable dt = new System.Data.DataTable();            dt.Columns.Add(name, System.Type.GetType("System.String"));            foreach ( String str in strarray)            {                DataRow dr = dt.NewRow();                dr[0] = str;                dt.Rows.Add(dr);            }            DataTabletoExcel(dt, path);        }        //导出到excel,需要导入Microsoft.Office.Interop.Excel        public static bool DataTabletoExcel(System.Data.DataTable dt, string AbosultedFilePath)        {            if (dt == null)                return false;            Microsoft.Office.Interop.Excel.Application excApp = new Microsoft.Office.Interop.Excel.Application();            if (excApp==null)            {                MessageBox.Show("无法创建excel对象,可能您的电脑未安装excel");                return false;            }            Microsoft.Office.Interop.Excel.Workbook workBook = excApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);            Microsoft.Office.Interop.Excel.Worksheet workSeet = workBook.Worksheets[1]; //取得sheet1            Microsoft.Office.Interop.Excel.Range range = null;            int tableCount = dt.Rows.Count;            int rowRead = 0;            float percent = 0;            for (int i = 0; i < dt.Columns.Count; i++)            {                workSeet.Cells[1, i + 1] = dt.Columns[i].ColumnName;                //设置标题的样式                range = (Microsoft.Office.Interop.Excel.Range)workSeet.Cells[1, i + 1];                range.Font.Bold = true; //粗体                range.Font.Size = "12";//字体大小                range.Font.Name = "宋体";                range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; //居中                range.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null); //背景色                range.EntireColumn.AutoFit(); //自动设置列宽                range.EntireRow.AutoFit(); //自动设置行高            }            for (int r = 0; r < dt.Rows.Count; r++)            {                for (int c = 0; c < dt.Columns.Count; c++)                {                    //写入内容                    workSeet.Cells[r + 2, c + 1] = "'" + dt.Rows[r][c].ToString();                    //设置样式                    range = (Microsoft.Office.Interop.Excel.Range)workSeet.Cells[r + 2, c + 1];                    range.Font.Size = 9; //字体大小                    range.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null); //加边框                    range.EntireColumn.AutoFit(); //自动调整列宽                }                rowRead++;                percent = ((float)(100 * rowRead)) / tableCount;                System.Windows.Forms.Application.DoEvents();            }            range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;            if (dt.Columns.Count > 1)            {                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;            }            try            {                workBook.Saved = true;                workBook.SaveCopyAs(AbosultedFilePath);            }            catch { }            workBook.Close();            if (excApp != null)            {                excApp.Workbooks.Close();                excApp.Quit();                int generation = System.GC.GetGeneration(excApp);                System.Runtime.InteropServices.Marshal.ReleaseComObject(excApp);                excApp = null;                System.GC.Collect(generation);            }            GC.Collect(); //强行销毁            #region 强行杀死最近打开的Excel进程            System.Diagnostics.Process[] excelProc = System.Diagnostics.Process.GetProcessesByName("EXCEL");            System.DateTime startTime = new DateTime();            int m, killID = 0;            for (m = 0; m < excelProc.Length; m++)            {                if (startTime < excelProc[m].StartTime)                {                    startTime = excelProc[m].StartTime;                    killID = m;                }            }            if (excelProc[killID].HasExited == false)            {                excelProc[killID].Kill();            }            #endregion            return true;        }        //导出到csv文件        public static void DataTabletocsv(System.Data.DataTable dt, string AbosultedFilePath)        {            //MessageBox.Show(AbosultedFilePath);            System.IO.FileStream fs = new FileStream(AbosultedFilePath, System.IO.FileMode.Create, System.IO.FileAccess.Write);            StreamWriter sw = new StreamWriter(fs, new System.Text.UnicodeEncoding());            //Tabel header            for (int i = 0; i < dt.Columns.Count; i++)            {                sw.Write(dt.Columns[i].ColumnName);                sw.Write("\t");            }            sw.WriteLine("");            //Table body            for (int i = 0; i < dt.Rows.Count; i++)            {                for (int j = 0; j < dt.Columns.Count; j++)                {                    sw.Write(DelQuota(dt.Rows[i][j].ToString()));                    sw.Write("\t");                }                sw.WriteLine("");            }            sw.Flush();            sw.Close();        }        //导入CSV文件        public static System.Data.DataTable OpenCSV(string fileName)        {            System.Data.DataTable dt = new System.Data.DataTable();            FileStream fs = new FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);            StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);            //记录每次读取的一行记录            string strLine = "";            //记录每行记录中的各字段内容            string[] aryLine;            //标示列数            int columnCount = 0;            //标示是否是读取的第一行            bool IsFirst = true;            //逐行读取CSV中的数据            while ((strLine = sr.ReadLine()) != null)            {                aryLine = strLine.Split(',');                if (IsFirst == true)                {                    IsFirst = false;                    columnCount = aryLine.Length;                    //创建列                    for (int i = 0; i < columnCount; i++)                    {                        DataColumn dc = new DataColumn(aryLine[i]);                        dt.Columns.Add(dc);                    }                }                else                {                    DataRow dr = dt.NewRow();                    for (int j = 0; j < columnCount; j++)                    {                        dr[j] = aryLine[j];                    }                    dt.Rows.Add(dr);                }            }            sr.Close();            fs.Close();            return dt;        }        public static string DelQuota(string str)        {            string result = str;            string[] strQuota = { "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "`", ";", "'", ",", ".", "/", ":", "/,", "<", ">", "?" };            for (int i = 0; i < strQuota.Length; i++)            {                if (result.IndexOf(strQuota[i]) > -1)                    result = result.Replace(strQuota[i], "");            }            return result;        }    }}
原创粉丝点击