此前必须导入EPPlus.dll、Excel.dll、ICSharpCode.SharpZipLib.dll这三个dll
读取Excel内容
public static int rowCount { get; private set; }
public static int columnsCount { get; private set; }
public static DataTableCollection Read(string excelPath, string excelName, string sheetName)
{
string path = excelPath + "/" + excelName;
Debug.Log(path);
FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelReader.AsDataSet();
rowCount = result.Tables[sheetName].Rows.Count;
columnsCount = result.Tables[sheetName].Columns.Count;
return result.Tables;
}
写入/修改Excel内容
public static void Write(string excelPath, string excelName, string sheetName, int row, int column,
string context)
{
string path = excelPath + "/" + excelName;
FileInfo newFile = new FileInfo(path);
using (ExcelPackage package = new ExcelPackage(newFile))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(sheetName);
worksheet.Cells[row, column].Value = context;
package.Save();
}
}
项目工程地址
|