#region 导出EXCEL
private void ExportExcels(List<DJMXView> djmxViewList)
{
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xlsx";
saveDialog.Filter = "Excel文件|*.xlsx";
saveDialog.FileName = $"{dateTimePicker_start.Text}_{dateTimePicker_end.Text}.xlsx";
if (saveDialog.ShowDialog() == DialogResult.OK)
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Workbooks books = excel.Workbooks;
Workbook xlbook = books.Add(true);
Worksheet xlsheet = (Worksheet)xlbook.ActiveSheet;
Type type = typeof(DJMXView);
//一共多少列
int colnum = type.GetProperties().Length;
//一共多少行
int rowNum = djmxViewList.Count+1;
//创建二维数组
Array arr = new object[rowNum, colnum];
//写入标题
for (int i = 0; i < colnum; i++)
{
PropertyInfo item = type.GetProperties()[i];
arr.SetValue(item.GetRemak(), 0, i);
}
//写入value
for (int i = 0; i < djmxViewList.Count; i++)
{
for (int j = 0; j < colnum; j++)
{
PropertyInfo item = type.GetProperties()[j];
// string str = $"{item.GetValue(djmxViewList[i], null)}".Replace("\n", "");
arr.SetValue(item.GetValue(djmxViewList[i]), i+1, j);
}
}
//一次性写入到excel的sheet中,减少对excel文件的I/O操作次数,提高效率
Range range = xlsheet.Range[xlsheet.Cells[1, 1], xlsheet.Cells[rowNum, colnum]];
range.Value2 = arr;
//excel表头添加背景色与字体颜色
Range rangeHeader = xlsheet.Range[xlsheet.Cells[1, 1], xlsheet.Cells[1, colnum]];
rangeHeader.Interior.Color = System.Drawing.Color.Teal;
rangeHeader.Font.Color = System.Drawing.Color.White;
excel.Columns.AutoFit();
xlbook.Saved = true;
xlbook.SaveCopyAs(saveDialog.FileName);
excel.Quit();
MessageBox.Show($"导出成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
#endregion
//提供一个额外的信息
[AttributeUsage(AttributeTargets.Enum | AttributeTargets.Property)]
public class RemarkAttribute:Attribute
{
public string Remark { get; private set; }
public RemarkAttribute(string remark)
{
this.Remark = remark;
}
}
//静态类
public static class RemarkExtend
{
//this 表示扩展方法
public static string GetRemak(this PropertyInfo propertyInfo)
{
if (propertyInfo.IsDefined(typeof(RemarkAttribute), true))
{
RemarkAttribute remarkAttribute = (RemarkAttribute)propertyInfo.GetCustomAttribute(typeof(RemarkAttribute));
return remarkAttribute.Remark;
}
else
{
return propertyInfo.Name;
}
}
}
Model如下
导出的EXCEL如下: