码迷,mamicode.com
首页 > 编程语言 > 详细

unity中使用excel导入和通过excel打印

时间:2021-04-29 11:38:52      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:inf   run   let   dialog   seq   row   lis   打开文件   package   

支持office和wps

using ExcelDataReader;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using UnityEngine;


public class Utils : MonoBehaviour
{
    private static int columnNum = 1000;
    private static int rowNum = 1000;


    /// <summary>
    /// 读取EXCEL表格
    /// </summary>
    /// <param name="filePath"></param>
    /// <param name="columnNum"></param>
    /// <param name="rowNum"></param>
    /// <returns></returns>
    private static DataTable ReadExcel(string filePath, ref int columnNum, ref int rowNum)
    {
        IExcelDataReader excelReader = null;
        FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
        var str = filePath.Split(.);
        if (str[1] == "xlsx")
        {

            excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
        }
        if (str[1] == "xls")
        {
            excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
        }

        DataSet result = excelReader.AsDataSet();

        stream.Close();
        columnNum = result.Tables[0].Columns.Count;
        rowNum = result.Tables[0].Rows.Count;

        return result.Tables[0];
    }

    /// <summary>
    /// 打印机打印
    /// </summary>
    private static void PrintByPrinter(string filePath)
    {
        Process process = new Process(); //系统进程
        process.StartInfo.CreateNoWindow = true; //不显示调用程序窗口
        process.StartInfo.UseShellExecute = true; //采用操作系统自动识别模式
        process.StartInfo.FileName = filePath;
        process.StartInfo.Verb = "print"; //指定执行的动作,打印:print 打开:open …………
        process.Start(); //开始打印

        UnityEngine.Debug.Log("开始打印");
    }

    /// <summary>
    /// 打开文件浏览器选取文件,浏览器指的是选择文件的窗口
    /// </summary>
    public static List<Person> OpenProject()
    {
        OpenFileDlg pth = new OpenFileDlg();
        pth.structSize = Marshal.SizeOf(pth);
        pth.filter = "All files (*.*)|*.*";
        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 = UnityEngine.Application.dataPath.Replace("/", "\\") + "\\Resources"; //默认路径
        pth.title = "打开项目";
        pth.defExt = "dat";
        pth.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;
        if (OpenFileDialog.GetOpenFileName(pth))
        {
            string filepath = pth.file; //选择的文件路径;  

            return SaveMsg(filepath);
        }
        return null;
    }

    /// <summary>
    /// 打开文件浏览器保存文件,浏览器指的是选择文件的窗口
    /// </summary>
    public static void SaveProject(List<Score> list)
    {
        SaveFileDlg pth = new SaveFileDlg();
        pth.structSize = Marshal.SizeOf(pth);
        pth.filter = "All files (*.*)|*.*";
        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 = UnityEngine.Application.dataPath; //默认路径
        pth.title = "保存项目";
        pth.defExt = "xlsx";
        pth.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;
        if (SaveFileDialog.GetSaveFileName(pth))
        {
            string filepath = pth.file; //选择的文件路径;  
            SaveExcel(filepath, list);
        }
    }

    public static void SaveExcel(string filePath, List<Score> list)
    {
        FileInfo newFile = new FileInfo(filePath);

        //if (newFile.Exists)
        //{
        //    newFile.Delete();
        //    newFile = new FileInfo(filePath);
        //}
        using (ExcelPackage package = new ExcelPackage(newFile))
        {
            var workSheets = package.Workbook.Worksheets;

            ExcelWorksheet worksheet = null;

            if (workSheets.Count > 0)
                worksheet = workSheets["成绩单"];
            else
                worksheet = workSheets.Add("成绩单");

            //添加列名   *******A2
            worksheet.Cells[1, 1].Value = "序号";
            worksheet.Cells[1, 2].Value = "时间";
            worksheet.Cells[1, 3].Value = "总成绩";
            worksheet.Cells[1, 4].Value = "击中次数";
            worksheet.Cells[1, 5].Value = "脱靶次数";
            worksheet.Cells[1, 6].Value = "训练类型";
            worksheet.Cells[1, 7].Value = "训练主题";

            //添加数据   *******A3
            for (int i = 0; i < list.Count; i++)
            {
                worksheet.Cells["A" + (i + 2)].Value = i + 1;                   //序号
                worksheet.Cells["B" + (i + 2)].Value = list[i].createTime;      //时间
                worksheet.Cells["C" + (i + 2)].Value = list[i].totalScore;      //总成绩
                worksheet.Cells["D" + (i + 2)].Value = list[i].hitNum;          //击中次数
                worksheet.Cells["E" + (i + 2)].Value = list[i].missNum;         //拖把次数
                worksheet.Cells["F" + (i + 2)].Value = list[i].turnType;        //训练类型
                worksheet.Cells["G" + (i + 2)].Value = list[i].turnTheme;       //训练主题
            }
            package.Save();
            UnityEngine.Debug.Log("写入完成");

            PrintByPrinter(filePath);
        }
    }

    /// <summary>
    /// 保存数据
    /// </summary>
    /// <param name="filepath"></param>
    /// <returns></returns>
    private static List<Person> SaveMsg(string filepath)
    {
        var data = ReadExcel(filepath, ref columnNum, ref rowNum);

        List<Person> personList = new List<Person>();

        for (int i = 1; i < data.Rows.Count; i++)
        {
            var temp = data.Rows[i].ItemArray;
            Person person = new Person(temp[0].ToString(), temp[1].ToString(), temp[2].ToString(), temp[3].ToString());
            personList.Add(person);
        }
        return personList;
    }

}

/// <summary>
/// 文件日志类
/// </summary>
// [特性(布局种类.有序,字符集=字符集.自动)]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class ChinarFileDlog
{
    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 : ChinarFileDlog
{
}

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 : ChinarFileDlog
{
}

1

1

unity中使用excel导入和通过excel打印

标签:inf   run   let   dialog   seq   row   lis   打开文件   package   

原文地址:https://www.cnblogs.com/wrc-blog/p/14713667.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!