using System.IO;
using OfficeOpenXml;
引用命名空间
using (ExcelPackage package = new ExcelPackage(FileInfo))
{
xxxxxxx
}
创建一个Excel表的类型,传入一个FileInfo文件类型 写在using中可以在逻辑完成后释放创建消耗的资源
ExcelWorksheet worksheet = ExcelPackage(非静态变量名).Workbook.Worksheets.Add(string); 为Excel添加一页,参数一为页的名字
ExcelWorksheet(非静态变量名) .Cells[i,j].Value = string; 为第i行第j列写入一个数据,写入的是传入的数据
string = (string)ExcelWorksheet(非静态变量名) .Cells[i,j].Value 从Excel表中提取值第i行第j列的值并赋值给自己的变量
ExcelPackage(非静态变量名).Save() 保存自己写的表
读取表:
FileInfo newFile = new FileInfo("path"); //根据传入的路径找到文件
using (ExcelPackage package = new ExcelPackage(newFile))
{
}//分析读取出来的文件解析为Excel表
ExcelWorksheet worksheet = package.Workbook.Worksheets[str];//参数str表示了读取的表名
worksheet.Cells[y, x].Value//这个返回的就是表里面的值,如果没有值则返回null
PS:特别注意!!!!无论表的索引还是读取的格子位置都是从1开始,访问索引0会直接导致越界
写表示例:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using OfficeOpenXml;
public class XlsxExport : MonoBehaviour
{
public static void ExportXlsxFile(string[,] contents)
{
//列名称配表
string[] columnTableName = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
//指定默认路径
//string path = Application.dataPath + "/" + "UIPrefabExcel.xlsx";
//自己选择一个路径
try
{
string path = EditorUtility.SaveFilePanel("Save Excel File", "", "Result.xlsx", "xlsx");
FileInfo newFile = new FileInfo(path);
if (newFile.Exists)
{
newFile.Delete();
newFile = new FileInfo(path);
}
//通过ExcelPackage打开文件
using (ExcelPackage package = new ExcelPackage(newFile))
{
//添加sheet
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("sheet1");
//添加表头
for (int i = 0; i < array.Length( 这里写一个第一排需要的名称的string数组); i++)
{
worksheet.Cells[1, i + 1].Value = array[i]( 这里写一个第一排需要的名称的string数组);
}
for (int m = 0; m < contents.GetLength(0); m++)
{
for (int n = 0; n < contents.GetLength(1); n++)
{
worksheet.Cells[columnTableName[n] + (m + 2)].Value = contents[m, n];
}
}
package.Save();
Debug.Log("Create Success!");
}
}catch(System.Exception e)
{
Debug.Log(e);
}
}
}