导入库:EPPlus 大家可以自行下载
[MenuItem("Tools/测试写入Excel")]
public static void TextWriteExcel()
{
string xlsxPath = Application.dataPath + "/../Data/Excel/MonsterData.xlsx";
//创建文件
FileInfo xlsxFile = new FileInfo(xlsxPath);
DirectoryInfo dir = new DirectoryInfo(Application.dataPath + "/../Data/Excel");
if (!dir.Exists)
{
dir.Create();
}
if (xlsxFile.Exists)
{
xlsxFile.Delete();
xlsxFile = new FileInfo(xlsxPath);
}
using(ExcelPackage package =new ExcelPackage(xlsxFile))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("怪物配置");
//worksheet.DefaultColWidth = 10; //sheet 页 默认行宽度
//worksheet.DefaultRowHeight = 30; //sheet 页 默认列高度
//worksheet.TabColor = Color.blue;
//worksheet.Cells.Style.WrapText = true; //所有单元格自适应
//worksheet.InsertRow(); //插入列,从某一列开始插入多少列
//worksheet.InsertColumn(); //插入行,从某一行开始插入多少行
//worksheet.DeleteColumn(); //删除,从某一列开始删除多少行
//worksheet.DeleteRow(); //删除,从某一列开始删除多少列
//worksheet.Column(1).Width = 10; //设定某一行宽
//worksheet.Row(1).Height = 30;
//worksheet.Column(1).Hidden = true; //设置隐藏状态
//worksheet.Row(1).Hidden = true;
//worksheet.Column(1).Style.Locked = true;
//worksheet.Row(1).Style.Locked = true; //设置某一列锁定
//worksheet.Cells.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center; //设置整体对齐方式
worksheet.Cells.AutoFitColumns(); //自适应宽度
ExcelRange range = worksheet.Cells[1, 1];
range.Value = "测试ssss水水水水水水水水水水水水水水水水水水水ssssssssss";
range.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid; //MediumGray,单元格的样式
//range.Style.Fill.BackgroundColor.SetColor(); //设置颜色
//range.Style.Font.Color.SetColor(); //设置字体颜色
range.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center; //对齐方式
range.Style.WrapText = true; //自动换行
package.Save();
}
}