Epplus插件下载
提取码:selz
测试功能:通过输入框将数据写入Excel表格。
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using OfficeOpenXml;//添加引用
/// <summary>
/// 测试创建Excel并写入数据
/// </summary>
public class WriteExcel : MonoBehaviour {
public InputField name;//姓名
public InputField nickName;//绰号
public InputField Kungfu;//功夫
public string ExcelName;//表格文件名
string outPath;//输出路径
FileInfo newFile;
void Start ()
{
outPath = string.Format(@"C:\Users\USER\Desktop\{0}.xlsx", ExcelName);
newFile = new FileInfo(outPath);
if (System.IO.File.Exists(outPath))
{
print("检测到Excel文件存在,请继续。");
}
else
{
Create();
}
}
/// <summary>
/// 创建Excel文件
/// </summary>
void Create()
{
if (newFile.Exists)
{
newFile.Delete(); // 确保创建新工作簿
newFile = new FileInfo(outPath);
}
//所有操作语句要放到using中
using (ExcelPackage package = new ExcelPackage(newFile))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1");//添加sheet
worksheet.DefaultColWidth = 15; //默认列宽
worksheet.DefaultRowHeight = 20; //默认行高
worksheet.Cells[1, 1].Value = "姓名";
worksheet.Cells[1, 2].Value = "绰号";
worksheet.Cells[1, 3].Value = "武功";
package.Save();
print("已创建Excel文件到桌面,请继续。");
}
}
/// <summary>
/// 写入数据
/// </summary>
public void Write()
{
if(name.text==string.Empty||name.text==""||
nickName.text == string.Empty || nickName.text == "" ||
Kungfu.text == string.Empty || Kungfu.text == "")
{
print("输入框未传值空");
return;
}
//所有操作语句要放到using中
using (ExcelPackage package = new ExcelPackage(newFile))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];//第一页Sheet
//获得最大行数
int MaxRowIndex = worksheet.Dimension.End.Row;
//写入
worksheet.Cells[MaxRowIndex + 1, 1].Value = name.text;
worksheet.Cells[MaxRowIndex + 1, 2].Value = nickName.text;
worksheet.Cells[MaxRowIndex + 1, 3].Value = Kungfu.text;
//保存
package.Save();
//清空输入框
name.text = "";
nickName.text = "";
Kungfu.text = "";
}
}
}