首页 > 其他分享 >导入导出

导入导出

时间:2024-02-22 14:22:05浏览次数:28  
标签:string 导出 sheetName 导入 new dt null DataTable

JSON导入导出

导入

OpenFileDialog openFileDialog = new OpenFileDialog()
{
    Filter = "JSON 源文件|*.json",
    Title = "导入",
    RestoreDirectory = true,
};
if (openFileDialog.ShowDialog() == true)
{
    try
    {
       ///**执行语句**///
    }
    catch (Exception)
    {
        MessageBox.Show("导入失败!");
    }
}

导出

 SaveFileDialog sfd = new SaveFileDialog()
 {
     Filter = "JSON 源文件|*.json",
     Title = "导出",
     FileName = "export",
     RestoreDirectory = true,
 };
 if (sfd.ShowDialog() == true)
 {
    ///**执行语句**///
 }

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

标签:string,导出,sheetName,导入,new,dt,null,DataTable
From: https://www.cnblogs.com/CloakBlowing/p/18027188

相关文章

  • 如何将数据库结构导入到PowerDesigner中
    1.点击File->ReverseEngineer->DataBase 2.弹出弹框,对模型进行命名,同时在DBMS中选择对应的数据库类型,点击确定 3.新弹框选择usingscriptfiles,去选择要导入的脚本,点击确定 4.即可成功导入数据库,效果如下 ......
  • 实现多个csv文件导出
    publicR<Boolean>exportCsv(HttpServletResponseresponse,@RequestBodyDrQueryDtoqueryDto)throwsException{IntegercountyId=queryDto.getCountyId();StringyearAnnual=queryDto.getYearAnnual();Stringurl="E:\\......
  • import { flattenKeys } from '.'; 是从哪里导入的flattenKeys
    import{flattenKeys}from'.';这行代码是从当前目录(currentdirectory)导入名为flattenKeys的函数或变量。在Node.js项目中,.表示当前目录的入口文件,通常是index.js或者与当前文件在同一目录下的其他导出模块。这意味着你在这个项目的某个文件夹内有一个文件(例如index.......
  • Java导入功能实现
    今天记录一下Java实现导入数据到数据,导入失败显示如下,会告诉你哪里出错了。controller代码实现@Operation(summary="导入工单")@PostMapping("/importOrderData")publicBaseResponse<String>importOrderData(@RequestParam@Parameter(name="excelFile",......
  • 将SquareLine Studio导出的LVGL代码在windows上运行
    1.引入SDL驱动SquareLineStudio导出的LVGL代码后如果要在windows上运行需要引入SDL的驱动,官方导出的代码是没有的,这里提供一个自己在网上找到的SDL2-2.28.1包,解压后放在同一目录下即可2.编写CmakeLists.txt这里提供我这边自己修改的CmakeLists.txtcmake_minimum_required(......
  • 【不背单词】生词本单词导出
    原文持续更新中:https://www.cnblogs.com/MrFlySand/p/18024734操作流程点击我-安装打开【不背单词】-【我的生词】开启程序点击【导出】(注:不用显示所有的单词也可进行导出)效果图点击链接,与我一起学习https://pd.qq.com/s/c01padly......
  • scss 中公共变量的导出方法:export
    scss中公共变量的导出方法:export:https://blog.csdn.net/ww_5211314/article/details/109614511?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522170848176116800180690474%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=170......
  • 导出程序EXCEL OLE DOI
    *&---------------------------------------------------------------------**&ReportZLOAD*&---------------------------------------------------------------------**&*&--------------------------------------------------------------------......
  • 请求接口生成导入模板
    这里介绍一种通过接口去生成导入数据Excel模板1、controller 2、serviceImpl@OverridepublicvoiddownloadOrderTemplate(HttpServletResponseresponse){List<WorkOrderVoImportDto>orderVoImports=newArrayList<>();try{List......
  • torch导出onnx示例-yolo
    onnx导出示例目录onnx导出示例yolov5导出源码导出参数模型可视化onnx推理yolov8导出源码onnx推理参考资料yolov5yolov5是一种目标检测算法,通过使用深度学习算法,可以通过输入图像,输出图像中存在的目标的种类和位置等信息。yolov5onnx则是在此基础上,通过使用onnx技术,将yolov5模......