创建Excel文件
注:导入配置文件org.in2bits.MyXls.dll,引入using org.in2bits.MyXls;
using UnityEngine;
using System.Collections;
using org.in2bits.MyXls;
using System.Collections.Generic;
public class TestInfo
{
public string name;
public string id;
public string num;
};
public class CreateExcel {
//创建单例模式,方便外部调用
private static CreateExcel eInstance;
public static CreateExcel GetInstance()
{
if(eInstance==null)
{
eInstance = new CreateExcel();
}
return eInstance;
}
//创建Excel(文件名,数据信息)
public void ExcelMaker(string name, List<TestInfo> listInfo)
{
XlsDocument xls = new XlsDocument();//新建一个xls文档
xls.FileName = name;
xls.SummaryInformation.Author = "zp"; //填加xls文件作者信息
xls.SummaryInformation.Subject = "test";//填加文件主题信息
string sheetName = "Sheet0";//xls文件中的第一页
Worksheet sheet = xls.Workbook.Worksheets.AddNamed(sheetName);//填加名为"chc 实例"的sheet页
Cells cells = sheet.Cells;//Cells实例是sheet页中单元格(cell)集合
int rowNum = listInfo.Count; //信息总数
int rowMin = 1;
int row = 0;
for (int x = 0; x < rowNum + 1; x++)
{
if (x == 0)
{
//根据具体的物体信息 .需要重新写
cells.Add(1, 1, "ID");
cells.Add(1, 2, "名字");
cells.Add(1, 3, "数量");
}
else
{
cells.Add(rowMin + x, 1, listInfo[row].id);
cells.Add(rowMin + x, 2, listInfo[row].name);
cells.Add(rowMin + x, 3, listInfo[row].num);
row++;//第几个数据,依次累加
}
}
xls.Save(); //把数据保存到Excel文件中
}
}
测试数据
using UnityEngine;
using System.Collections;
using System.IO;
using org.in2bits.MyXls;
using System;
using System.Collections.Generic;
public class Test : MonoBehaviour
{
private string path;
private TestInfo test1;
private TestInfo test2;
private TestInfo test3;
private List<TestInfo> listInfos = new List<TestInfo>();
void Start()
{
#region//测试数据
test1 = new TestInfo();
test1.id = "0";
test1.name = "Miki";
test1.num = "221";
test2 = new TestInfo();
test2.id = "1";
test2.name = "Harry";
test2.num = "23";
test3 = new TestInfo();
test3.id = "2";
test3.name = "Kevin";
test3.num = "43";
listInfos.Add(test1);
listInfos.Add(test2);
listInfos.Add(test3);
#endregion
print (Application.dataPath);
}
void OnGUI()
{
if (GUI.Button(new Rect(400, 200, 200, 100), "CreateExcel"))
{
PrintExcel();
Debug.Log("创建成功");
}
}
public void PrintExcel()
{
if (!Directory.Exists(Application.dataPath + "/Prints"))
{
Directory.CreateDirectory(Application.dataPath + "/Prints");
}
path = Application.dataPath + "/Prints/Excel_"
+ System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ".xls";
CreateExcel.GetInstance().ExcelMaker(path, listInfos);
}
}