导入导出

JSON导入导出

导入

OpenFileDialog openFileDialog = new OpenFileDialog()
{
    Filter = "JSON 源文件|*.json",
    Title = "导入",
    RestoreDirectory = true,
};
if (openFileDialog.ShowDialog() == true)
{
    try
    {
       string json = File.ReadAllText(openFileDialog.FileName, System.Text.Encoding.UTF8);
       IOModel m = System.Text.Json.JsonSerializer.Deserialize<IOModel>(json);
       ///**执行语句**///
    }
    catch (Exception)
    {
        MessageBox.Show("导入失败!");
    }
}

导出

 SaveFileDialog sfd = new SaveFileDialog()
 {
     Filter = "JSON 源文件|*.json",
     Title = "导出",
     FileName = "export",
     RestoreDirectory = true,
 };
 if (sfd.ShowDialog() == true)
 {
    string jsonItems = System.Text.Json.JsonSerializer.Serialize(m);
    File.WriteAllText(sfd.FileName, jsonItems, System.Text.Encoding.UTF8);
    ///**执行语句**///
 }

exel导入导出

准备

点击查看代码
using System.Collections.ObjectModel;
using System.Reflection;
using System;
using System.Collections;
using System.Linq;
using System.Windows;
using System.Windows.Media.Media3D;
using System.Text.RegularExpressions;

/// <summary>
/// Npoi操作Excel类
/// </summary>
public static class NpoiExcelHelper
{
    /// <summary>
    /// 根据Excel文件类型返回IWorkbook
    /// </summary>
    /// <param name="fileName">文件路径/文件名称(含后缀名)</param>
    /// <param name="rowNum">Excel行数</param>
    /// <param name="colNum">Excel列数</param>
    /// <param name="isFirstRowColumn">第一行是否是标题</param>
    /// <returns></returns>
    public static IWorkbook GetWorkbook(string fileName, out int rowNum, out int colNum, bool isFirstRowColumn = true)
    {
        bool isXlsx = Path.GetExtension(fileName).Equals(".xlsx");
        if (isXlsx)
        {
            if (isFirstRowColumn)
            {
                rowNum = 1048575;
            }
            else
            {
                rowNum = 1048576;
            }
            colNum = 16384;
        }
        else
        {
            if (isFirstRowColumn)
            {
                rowNum = 65535;
            }
            else
            {
                rowNum = 65536;
            }
            colNum = 256;
        }

        if (File.Exists(fileName))
        {

            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                if (isXlsx)
                {
                    return new XSSFWorkbook(fs);
                }
                else
                {
                    return new HSSFWorkbook(fs);
                }
            }
        }
        else
        {
            if (isXlsx)
            {
                return new XSSFWorkbook();
            }
            else
            {
                return new HSSFWorkbook();
            }
        }
    }

    /// <summary>
    /// 将DataTable中的数据导入到excel中(第一行是标题)
    /// 支持根据Excel数据自动分页(多个Sheet)
    /// </summary>
    /// <param name="dt">DataTable</param>
    /// <param name="fileName">文件路径/文件名称(含后缀名)</param>
    /// <param name="columnFieldText">字段对应中文 顺序需要跟Excel中数据顺序一致</param>
    /// <param name="sheetName">Excel中Sheet名称(多个sheet时 名字后面自动加上数字序号)</param>
    /// <returns></returns>
    public static int DataTableToExcel(DataTable dt, string fileName, string[,] columnFieldText = null, string sheetName = null)
    {
        int rowNum = 0;
        int colNum = 0;
        IWorkbook workbook = GetWorkbook(fileName, out rowNum, out colNum);

        var recordNum = dt.Rows.Count;
        int totalPage = recordNum % rowNum == 0 ? recordNum / rowNum : recordNum / rowNum + 1;

        for (var p = 0; p < totalPage; p++)
        {
            if (string.IsNullOrEmpty(sheetName))
            {
                sheetName = dt.TableName;
            }

            if (totalPage > 1)
            {
                if (string.IsNullOrEmpty(sheetName))
                {
                    sheetName = "Sheet";
                }

                sheetName = sheetName + (p + 1).ToString();
            }
            else
            {
                if (string.IsNullOrEmpty(sheetName))
                {
                    sheetName = "Sheet1";
                }
            }

            ISheet sheet;//创建工作表
            if (workbook.GetSheet(sheetName) != null)
            {
                sheet = workbook.GetSheet(sheetName);
            }
            else
            {
                sheet = workbook.CreateSheet(sheetName);
            }


            #region 标题
            IRow row = sheet.CreateRow(0);//在工作表中添加一行
            if (columnFieldText != null)
            {
                var dataColumn = columnFieldText.GetLength(0);
                if (dataColumn <= colNum)
                {
                    for (int m = 0; m < dataColumn; m++)
                    {
                        ICell cell = row.CreateCell(m);//在行中添加一列
                        cell.SetCellValue(columnFieldText[m, 1]);//设置列的内容
                    }
                }
                else
                {
                    //数据列数超过了Excel的列数
                }
            }
            else
            {
                var dataColumn = dt.Columns.Count;
                if (dataColumn <= colNum)
                {
                    for (int i = 0; i < dataColumn; i++)
                    {
                        ICell cell = row.CreateCell(i);//在行中添加一列
                        cell.SetCellValue(dt.Columns[i].ColumnName);//设置列的内容     
                    }
                }
                else
                {
                    //数据列数超过了Excel的列数
                }
            }
            #endregion
            #region 填充数据

            int startIndex = p * rowNum;
            int endindex = (p + 1) * rowNum - 1;
            if (endindex >= recordNum)
            {
                endindex = recordNum - 1;
            }

            for (int i = startIndex; i <= endindex; i++)//遍历DataTable行
            {
                DataRow dataRow = dt.Rows[i];

                row = sheet.CreateRow(i - startIndex + 1);//在工作表中添加一行

                if (columnFieldText != null)
                {
                    var dataColumn = columnFieldText.GetLength(0);
                    if (dataColumn <= colNum)
                    {
                        for (int m = 0; m < dataColumn; m++)
                        {
                            ICell cell = row.CreateCell(m);//在行中添加一列
                            cell.SetCellValue(dataRow[columnFieldText[m, 0]].ToString());//设置列的内容
                        }
                    }
                    else
                    {
                        //数据列数超过了Excel的列数
                    }
                }
                else
                {
                    var dataColumn = dt.Columns.Count;
                    if (dataColumn <= colNum)
                    {
                        for (int j = 0; j < dt.Columns.Count; j++)//遍历DataTable列
                        {
                            ICell cell = row.CreateCell(j);//在行中添加一列
                            cell.SetCellValue(dataRow[j].ToString());//设置列的内容     
                        }
                    }
                    else
                    {
                        //数据列数超过了Excel的列数
                    }
                }
            }
            #endregion
        }
        #region 输出Excel
        using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write))
        {
            workbook.Write(fs);
            fs.Close();
            return dt.Rows.Count;
        }
        #endregion
    }

    /// <summary>
    /// 将excel中的数据导入到DataTable中(第一行是标题)
    /// 支持多个sheet数据导入(建议多个sheet的数据格式保持一致,将没有数据的sheet删除)
    /// </summary>
    /// <param name="fileName">文件路径(含文件名称后缀名)</param>
    /// <param name="columnFieldText">字段对应中文 顺序需要跟Excel中数据顺序一致</param>
    /// <param name="sheetName">指定Excel中Sheet名称 如果为null时,读取所有sheet中的数据</param>
    /// <returns>返回的DataTable</returns>
    public static DataTable ExcelToDataTable(string fileName, string[,] columnFieldText = null, string sheetName = null)
    {
        DataTable data = new DataTable();
        int rowNum = 0;
        int colNum = 0;
        IWorkbook workbook = GetWorkbook(fileName, out rowNum, out colNum);

        for (int e = 0; e < workbook.NumberOfSheets; e++)
        {
            //ISheet sheet = workbook.GetSheetAt(e
            ISheet sheet = workbook.GetSheet(sheetName);
            if (sheet != null)
            {
                var currentSheetIndex = 0;
                if (!string.IsNullOrEmpty(sheetName))
                {
                    if (sheet.SheetName == sheetName)
                    {
                        currentSheetIndex = e;
                    }
                }

                IRow firstRow = sheet.GetRow(0);
                if (firstRow != null)
                {
                    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                    var dataColumn = columnFieldText != null ? columnFieldText.GetLength(0) : cellCount;
                    int startRow = sheet.FirstRowNum;
                    if (dataColumn <= colNum)
                    {
                        if (e == currentSheetIndex)
                        {
                            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((columnFieldText != null ? columnFieldText[i, 0] : cellValue));
                                        //data.Columns.Remove(column);
                                        data.Columns.Add(column);
                                    }
                                }
                            }
                        }

                        startRow = sheet.FirstRowNum + 1;

                        //最后一列的标号
                        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();
                            for (int j = row.FirstCellNum; j < cellCount; ++j)
                            {
                                if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
                                    dataRow[j] = row.GetCell(j).ToString();
                            }
                            data.Rows.Add(dataRow);
                        }
                    }
                    else
                    {
                        //数据列数超过了Excel的列数
                    }
                }

                if (!string.IsNullOrEmpty(sheetName))
                {
                    if (sheet.SheetName == sheetName)
                    {
                        break;
                    }
                }
            }
        }
        return data;
    }

    #region 类型转换
    /// <summary>
    /// DataTable 转换为List 集合
    /// </summary>
    /// <typeparam name="TResult">类型</typeparam>
    /// <param name="dt">DataTable</param>
    /// <returns></returns>
    public static ObservableCollection<TResult> ToObservableCollection<TResult>(DataTable dt) where TResult : class, new()
    {
        //创建一个属性的列表
        List<PropertyInfo> prlist = new List<PropertyInfo>();
        //获取TResult的类型实例  反射的入口
        Type t = typeof(TResult);
        //获得TResult 的所有的Public 属性 并找出TResult属性和DataTable的列名称相同的属性(PropertyInfo) 并加入到属性列表 
        Array.ForEach<PropertyInfo>(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); });
        //创建返回的集合
        ObservableCollection<TResult> oblist = new ObservableCollection<TResult>();

        foreach (DataRow row in dt.Rows)
        {
            //创建TResult的实例
            TResult ob = new TResult();
            //找到对应的数据  并赋值
            prlist.ForEach(p => {
                if (row[p.Name] != DBNull.Value)
                {
                    if (p.PropertyType == typeof(int) || p.PropertyType == typeof(int?))
                    {
                        p.SetValue(ob, int.Parse(row[p.Name].ToString()), null);
                    }
                    else if (p.PropertyType == typeof(string))
                    {
                        p.SetValue(ob, row[p.Name], null);
                    }
                    else if (p.PropertyType == typeof(double))
                    {
                        p.SetValue(ob, double.Parse(row[p.Name].ToString()), null);
                    }
                    else if (p.PropertyType == typeof(Point))
                    {
                        p.SetValue(ob, Point.Parse(row[p.Name].ToString()), null);
                    }
                    else
                    {
                        p.SetValue(ob, Point3D.Parse(row[p.Name].ToString()), null);
                    }
                }

            });
            //放入到返回的集合中.
            oblist.Add(ob);
        }
        return oblist;
    }

    /// <summary>
    /// 转换为一个DataTable
    /// </summary>
    /// <typeparam name="TResult"></typeparam>
    /// <param name = "value" ></ param >
    /// <returns></returns>
    public static DataTable ToDataTable(IEnumerable list)
    {
        //创建属性的集合
        List<PropertyInfo> pList = new List<PropertyInfo>();
        //获得反射的入口
        Type type = list.AsQueryable().ElementType;
        DataTable dt = new DataTable();
        //把所有的public属性加入到集合 并添加DataTable的列
        Array.ForEach<PropertyInfo>(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); });
        foreach (var item in list)
        {
            //创建一个DataRow实例
            DataRow row = dt.NewRow();
            //给row 赋值
            pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
            //加入到DataTable
            dt.Rows.Add(row);
        }
        return dt;
    }


    /// <summary>
    /// 转换为一个DataTable
    /// </summary>
    /// <typeparam name="TResult"></typeparam>
    /// <param name = "value" ></ param >
    /// <returns></returns>
    public static DataTable ToDataTable<TResult>(IEnumerable<TResult> value) where TResult : class
    {
        //创建属性的集合
        List<PropertyInfo> pList = new List<PropertyInfo>();
        //获得反射的入口
        Type type = typeof(TResult);
        DataTable dt = new DataTable();
        //把所有的public属性加入到集合 并添加DataTable的列
        Array.ForEach<PropertyInfo>(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); });
        foreach (var item in value)
        {
            //创建一个DataRow实例
            DataRow row = dt.NewRow();
            //给row 赋值
            pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
            //加入到DataTable
            dt.Rows.Add(row);
        }
        return dt;
    }
    #endregion

    public static bool HasChinese(string str)
    {
        return Regex.IsMatch(str, @"[\u4e00-\u9fa5]");
    }

    public static DataTable HashTableToDataTable(Hashtable ht)
    {
        try
        {
            //创建DataTable
            DataTable dt = new DataTable();
            //创建新列
            foreach (DictionaryEntry element in ht)
            {
                DataColumn dc = dt.Columns.Add(element.Key.ToString(), typeof(string));
            }
            //将HashTable中的值添加到DataTable中
            DataRow dr = dt.NewRow();
            foreach (DictionaryEntry element in ht)
            {
                //dr["dc1"] = (string)element.Key;
                dr[(string)element.Key] = element.Value.ToString();
            }
            dt.Rows.Add(dr);
            return dt;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

导入

Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog()
    {
        Filter = "excel文件(*.xlsx,*.xls)|*.xlsx;*.xls",
        Title = "导入",
        RestoreDirectory = true,
    };
  
    if (dialog.ShowDialog() == true)
    {
        var v = parameter as CreateNodesViewModel;
        List<MyCustomPart> customParts = new List<MyCustomPart>();
        string fileName = dialog.FileName;
        string sheetName1 = "Sheet1";

        string[,] columnFieldText = null;
        var date= NpoiExcelHelper.ExcelToDataTable(fileName, columnFieldText, sheetName1);
    }       

导出

 Microsoft.Win32.SaveFileDialog dialog = new Microsoft.Win32.SaveFileDialog()
 {
     Filter = "excel文件(*.xlsx,*.xls)|*.xlsx;*.xls",
     Title = "导出",
     FileName = "导出",
     RestoreDirectory = true,
 };
 if (dialog.ShowDialog() == true)
 {
     string fileName = dialog.FileName;
     string sheetName = "Sheet1";
     string[,] columnFieldText = null;
     NpoiExcelHelper.DataTableToExcel(dataTable, fileName, columnFieldText, sheetName);
 }
posted @ 2024-02-22 14:19  披着披风吹着风  阅读(1)  评论(0编辑  收藏  举报