读取EXCEL需要引入
using System.IO;
using OfficeOpenXml;
两个头文件
下载地址
下载地址
依次在Assets目录下建立StreamingAssets目录及子目录建立Excel目录,把自己空的.xlsx模版文件放到这个目录下面
这是我的空模版
void SaveExcel(List<Dictionary<DataInfo_Enum, string>> ExcelData)
{
DateTime NowTime = DateTime.Now.ToLocalTime();
if (ExcelData != null)
{
string a = NowTime.ToString("yyyy-MM-dd").Replace("-", "");
string b = NowTime.ToString("MM-dd HH:mm:ss").Replace("-", "/");
string m_fileName = Application.streamingAssetsPath;
if (!m_fileName.EndsWith("\\")) m_fileName += "\\";
m_fileName += "Excel";
if (!Directory.Exists(m_fileName)) Directory.CreateDirectory(m_fileName);
m_fileName += "\\excel.xlsx";
//设置保存目录
string path = @"D:/汽蚀实验报告";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
DirectoryInfo direction = new DirectoryInfo(path);
FileInfo[] files = direction.GetFiles("*", SearchOption.AllDirectories);
string tempStr = "/" + a + (files.Length+1).ToString("000");
string filepath = path + @tempStr + ".xlsx";
//string filepath = path + @"/汽蚀实验报告"+ ".xlsx";
//if (!File.Exists(filepath))
//{
// File.Create(filepath);
//}
myReportPanel_Manager.ExcelPath = filepath;
FileInfo m_file = new FileInfo(filepath);
using (ExcelPackage package = new ExcelPackage(new FileStream(m_fileName, FileMode.Open)))
{
for (int i = 1; i <= package.Workbook.Worksheets.Count; ++i)
{
ExcelWorksheet sheet = package.Workbook.Worksheets[i];
if (i == 1)
{
//第一表单的7行4列填入 我是以该文件夹文件个数加+1来命名的
sheet.Cells[7, 4].Value = a + (files.Length + 1).ToString("000");
sheet.Cells[9, 4].Value = NowTime.ToString("yyyy-MM-dd").Replace("-", "/");
sheet.Cells[11, 4].Value = NowTime.ToString("hh:mm:ss");
}
if (i == 2)
{
//第二表单的3行7列填入 我是以该文件夹文件个数加+1来命名的
//3行13列填入 当前实验单生成的时间
sheet.Cells[3, 7].Value = a + (files.Length + 1).ToString("000");
sheet.Cells[3, 13].Value = b;
//循环读取我的列表字典
for (int j = 0; j < ExcelData.Count; j++)
{
List<string> tempStringList = new List<string>();
foreach (var item in ExcelData[j].Values)
{
tempStringList.Add(item);
}
for (int k = 1; k < tempStringList.Count; k++)
{
sheet.Cells[14 + j, 1 + k].Value = float.Parse(tempStringList[k]);
}
}
}
}
package.SaveAs(m_file);
}
}
}
注意package.Workbook.Worksheets[1]对应的是EXCEL的下面的三个表单的第一个表单 没有0号