当前位置:   article > 正文

使用Uni-Excel插件在unity中读写excel 还可通过选择目录的方式保存

uni-excel

插件连接插件地址

导入插件后如果报system.data冲突的错误 只需要把导入的插件下的plugins的system.data这个程序集删除
我这里已经删除过了
我这里已经删除过了
找了很好用的excel读写dll 基于EPPlus.dll
https://www.yuque.com/docs/share/da66bf97-fdad-4db9-820c-8dfd82163c54?# 《Excel读写插件 EPPlus.Dll》

新建场景

自己创建个button 点击button出现选择保存目录的提示框

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.HSSF.Util;

using System.IO;
using Excel;
using System.Data;
using ArabicSupport;
using Common;
using UnityEngine.UI;
using System;

public class ReadOrWrieExcel : MonoBehaviour
{
    public string MySheetName = "mytest1";//Excel工作表的名字
    public string MyExcelName = "MyTest";//Excel的名字

    public List<string> MyCellArray;//第一列数据
    public List<string> MyCellArray02;//第二列数据
    public List<string> MyCellArray03;//第san列数据

    public List<string> MyString;//用于ExcelDataReader数据读取

    //private bool ReadEcelxEnable_NPOI = false;//启用禁用NPOI组件
    //private bool ReadEcelxEnable_ExcelDataReader = false;//启用禁用ExcelDataReader组件

    FileStream myaddress;
    public Button but;
    private void OnEnable()
    {
        //通过点击按钮 实现选择文件路径 然后保存excel文件
        but.onClick.AddListener(() =>
        {
            SaveProject(MyCellArray, MyCellArray02, MyCellArray03);
        });
    }



    public void Start()
    {
    //**如果不使用保存目录提示框 可以借鉴这里**
        //StartCoroutine(Test());
    }

    //测试读写
    IEnumerator Test()
    {

        ExcelDataWrite(Application.dataPath + "/StreamingAssets/" + MyExcelName + ".xls", MyCellArray, MyCellArray02, MyCellArray03);
        yield return new WaitForSeconds(1f);

        // ExcelDataRead(Application.dataPath + "/StreamingAssets/" + MyExcelName + ".xls");
    }

    /// <summary>
    ///  //通过选择存储目录的方式 保存excel文件
    /// </summary>
    /// <param name="str">存放的每一列数据  可以是多个 第一个list最好为最大行数</param>
    public void SaveProject(params List<string>[] str)
    {
        SaveFileDlg pth = new SaveFileDlg();
        pth.structSize = System.Runtime.InteropServices.Marshal.SizeOf(pth);
        pth.filter = "xls (*.xls)";
        pth.file = new string(new char[256]);
        pth.maxFile = pth.file.Length;
        pth.fileTitle = new string(new char[64]);
        pth.maxFileTitle = pth.fileTitle.Length;
        pth.initialDir = Application.dataPath;  // default path  
        pth.title = "保存项目";
        pth.defExt = "xls";
        pth.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;
        if (SaveFileDialog.GetSaveFileName(pth))
        {
            string filepath = pth.file;//选择的文件路径; 


            //通过获取到的路径 保存excel文件


            ExcelDataWrite(filepath, str);
            Debug.Log(filepath);
        }
    }
    /// <summary>
    /// excel写入数据
    /// </summary>
    /// <param name="filePath">w文件路径</param>
    /// <param name="ss">存放每一列数据的数组  可以是多个 第一个list最好为最大行数</param>
    public void ExcelDataWrite(string filePath, params List<string>[] ss)
    {
        #region
        //if (Directory.Exists(Application.dataPath+ "/StreamingAssets/" + MyExcelName + ".xls")==false)
        //{
        //     myaddress = new FileStream(Application.dataPath + "/StreamingAssets/" + MyExcelName + ".xls", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
        //}
        //else
        //{
        //     myaddress = new FileStream(Application.dataPath + "/StreamingAssets/" + MyExcelName + ".xls", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
        //}
        #endregion
        //myaddress = new FileStream(Application.dataPath + "/StreamingAssets/" + MyExcelName + ".xls", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
        myaddress = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
        HSSFWorkbook MyWorkbook = new HSSFWorkbook();//创建一个空的Excel文件
        HSSFSheet sheet01 = (HSSFSheet)MyWorkbook.CreateSheet(MySheetName);//添加第一个工作表

       //存储多列数据  数据长度可以不一样(看自己需求更改)
        for (int i = 0; i < ss[0].Count; i++)
        {
            HSSFRow Row = (HSSFRow)sheet01.CreateRow((short)i);//为工作表定义行       
            for (int a = 0; a < ss.Length; a++)
            {
                HSSFCell cell = (HSSFCell)Row.CreateCell((short)a);

                if (ss[a].Count > i)
                {
                    cell.SetCellValue(ss[a][i].ToString());//给第i列添加数值
                }
                else
                {
                    cell.SetCellValue("");
                }
            }

        }

            //根据自己需求 改
            //for (int i = 0; i < hangNum.Length; i++)
            //{
            //    HSSFRow Row = (HSSFRow)sheet01.CreateRow((short)i);//为工作表定义行 
            //    HSSFCell cell = (HSSFCell)Row.CreateCell((short)0);//为第i行  定义列
            //    cell.SetCellValue(hangNum[i]);//给第i列添加数值
            //    if (i < hang.Length)
            //    {
            //        HSSFCell cell02 = (HSSFCell)Row.CreateCell((short)1);
            //        cell02.SetCellValue(hang[i]);
            //    }
            //    else
            //    {
            //        HSSFCell cell02 = (HSSFCell)Row.CreateCell((short)1);
            //        cell02.SetCellValue("");
            //    }
            //    #region[格式设置]
            //    //Row.RowStyle = MyWorkbook.CreateCellStyle();//定义行样式
            //    //Row.RowStyle.BorderBottom = BorderStyle.Double;//更改行边界
            //    //cell.CellStyle = MyWorkbook.CreateCellStyle();//定义单元格格式
            //    //cell.CellStyle.BorderRight = BorderStyle.Thin;//改变一小格边界
            //    //cell.CellStyle.BorderBottom = BorderStyle.Dashed;
            //    //cell.CellStyle.BottomBorderColor = HSSFColor.Red.Index;

            //    //HSSFFont MyFont = (HSSFFont)MyWorkbook.CreateFont();//定义字体
            //    改变字体、字体高度、字体颜色、eto
            //    //MyFont.FontName = "Tahoma";
            //    //MyFont.FontHeightInPoints = 14;
            //    //MyFont.Color = HSSFColor.Gold.Index;
            //    //MyFont.Boldweight = (short)FontBoldWeight.Bold;

            //    //设置单元格字体
            //    //cell.CellStyle.SetFont(MyFont);
            //    #endregion
            //}

            MyWorkbook.Write(myaddress);//在Excel中写入数据
            MyWorkbook.Close();//关闭打开的excel
        }
    
        //读取excel文件数据
        public void ExcelDataRead(string filepaths)
        {
            HSSFWorkbook MyBook;
            //查找并打开excel文件
            using (FileStream MyAddress_read = new FileStream(filepaths, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                MyBook = new HSSFWorkbook(MyAddress_read);
            }
            //查找带有表单名称的表单
            ISheet sheet_read = MyBook.GetSheet(MySheetName);

            //表单最大行数据 sheet_read.LastRowNum
            for (int row = 0; row <= sheet_read.LastRowNum; row++)
            {
                //查找表行
                IRow row_read = sheet_read.GetRow(row);
                //每行最大列数据 row_read.LastCellNum;
                for (int cells = 0; cells < row_read.LastCellNum; cells++)
                {
                    //显示读取的excel内容
                    Debug.Log(row_read.GetCell(cells).ToString());
                    //支持阿拉伯语言
                    // Debug.Log(ArabicFixer.Fix(row_read.GetCell(cells).ToString()));

                }
            }
        }
    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199

保存目录提示框的实现方式 (基本设置)


using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
using System;

namespace Common
{
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public class FileDlg
    {
        public int structSize = 0;
        public IntPtr dlgOwner = IntPtr.Zero;
        public IntPtr instance = IntPtr.Zero;
        public String filter = null;
        public String customFilter = null;
        public int maxCustFilter = 0;
        public int filterIndex = 0;
        public String file = null;
        public int maxFile = 0;
        public String fileTitle = null;
        public int maxFileTitle = 0;
        public String initialDir = null;
        public String title = null;
        public int flags = 0;
        public short fileOffset = 0;
        public short fileExtension = 0;
        public String defExt = null;
        public IntPtr custData = IntPtr.Zero;
        public IntPtr hook = IntPtr.Zero;
        public String templateName = null;
        public IntPtr reservedPtr = IntPtr.Zero;
        public int reservedInt = 0;
        public int flagsEx = 0;
    }
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public class OpenFileDlg : FileDlg
    {

    }
    public class OpenFileDialog
    {
        [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
        public static extern bool GetOpenFileName([In, Out] OpenFileDlg ofd);
    }
    public class SaveFileDialog
    {
        [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
        public static extern bool GetSaveFileName([In, Out] SaveFileDlg ofd);
    }
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public class SaveFileDlg : FileDlg
    {

    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57

选择文件和选择文件地址

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Common;
public class FileControllor : MonoBehaviour
{
    //文件格式根据自己需求更改  .txt   .xls之类的
    private void Start()
    {
        //OpenProject();
       // SaveProject();
    }
    //选择一个文件的地址
    public void OpenProject()
    {
        OpenFileDlg pth = new OpenFileDlg();
        pth.structSize = System.Runtime.InteropServices.Marshal.SizeOf(pth);
        pth.filter = "txt (*.txt)";
        pth.file = new string(new char[256]);
        pth.maxFile = pth.file.Length;
        pth.fileTitle = new string(new char[64]);
        pth.maxFileTitle = pth.fileTitle.Length;
        pth.initialDir = Application.dataPath;  // default path  
        pth.title = "打开项目";
        pth.defExt = "txt";
        pth.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;
        //0x00080000   是否使用新版文件选择窗口
        //0x00000200   是否可以多选文件
        if (OpenFileDialog.GetOpenFileName(pth))
        {
            string filepath = pth.file;//选择的文件路径;  
            Debug.Log(filepath);
        }
    }
    //将文件保存到一个地址
    public void SaveProject()
    {
        SaveFileDlg pth = new SaveFileDlg();
        pth.structSize = System.Runtime.InteropServices.Marshal.SizeOf(pth);
        pth.filter = "xls (*.xls)";
        pth.file = new string(new char[256]);
        pth.maxFile = pth.file.Length;
        pth.fileTitle = new string(new char[64]);
        pth.maxFileTitle = pth.fileTitle.Length;
        pth.initialDir = Application.dataPath;  // default path  
        pth.title = "保存项目";
        pth.defExt = "xls";
        pth.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;
        if (SaveFileDialog.GetSaveFileName(pth))
        {
            string filepath = pth.file;//选择的文件路径;  
            Debug.Log(filepath);
        }
    }

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号