EPPlus

public string ImportError(List<User> users)
{
string date = DateTime.Now.ToString("yyyyMMdd");
string sWebRootFolder = Path.GetDirectoryName(typeof(UserController).Assembly.Location);
string sFileName = $"{DateTime.Now.ToString("MMddHHss")}-{Guid.NewGuid()}.xlsx";
string pathbase = $"{sWebRootFolder}/Upload/ExprotExcel/{date}/"; //保存路径
string url = $"/Upload/ExprotExcel/{date}/";
try
{
//转utf-8
UTF8Encoding utf8 = new UTF8Encoding();
byte[] buffer = utf8.GetBytes(sFileName);
sFileName = utf8.GetString(buffer);
//判断文件夹
if (!Directory.Exists(pathbase))
Directory.CreateDirectory(pathbase);
//判断同名文件
FileInfo file = new FileInfo(Path.Combine(pathbase, sFileName));
if (file.Exists)
{
//判断同名文件创建时间
file.Delete();
file = new FileInfo(Path.Combine(pathbase, sFileName));
}

using (ExcelPackage package = new ExcelPackage(file))
{
//添加worksheet
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1");
//添加表头
int column = 1;
string[] sColumnName = new string[] { "账号", "姓名", "性别", "机构" };
foreach (string cn in sColumnName)
{
worksheet.Cells[1, column].Value = cn.Trim();
worksheet.Cells[1, column].Style.Font.Bold = true;//字体为粗体
worksheet.Cells[1, column].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;//水平居中
//worksheet.Cells[1, column].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;//设置样式类型
//worksheet.Cells[1, column].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(159, 197, 232));//设置单元格背景色
column++;
}
//添加数据
int row = 2;

var list = new List<Object[]> { new object[] { "A", "B", "C" } };
var ws = package.Workbook.Worksheets.Add("Sheet2");
ws.Cells["A1"].LoadFromArrays(list);

foreach (var dr in users)
{

worksheet.Cells[row, 1].Value = dr.MobilePhone;
worksheet.Cells[row, 2].Value = dr.RealName;
worksheet.Cells[row, 3].Value = 5;
worksheet.Cells[row, 4].Value = dr.OrgName;

var val = worksheet.DataValidations.AddListValidation(worksheet.Cells[row, 3].Address);//设置下拉框显示的数据区域
val.Formula.ExcelFormula = "=(Sheet2!$A$1:$C$1)";//数据区域的名称
val.Prompt = "选择";//下拉提示
val.ShowInputMessage = true;//显示提示内容

row++;
}
//自动列宽
worksheet.Cells.AutoFitColumns();
//保存
package.Save();
return url + sFileName;
}
}
catch (Exception ex)
{
throw;
return string.Empty;
}
}

上一篇:SQL WHERE 语法


下一篇:FastAPI(六十五)实战开发《在线课程学习系统》基础架构的搭建