三个有用的相关代码sn-ps:
- 带有 EPPlus 的 ListToExcel 的 C# 扩展方法:
public static void ListToExcel<T>(this IList<T> list, string filename, bool isRtl)
{
var response = HttpContext.Current.Response;
var path = HttpUtility.UrlEncode(filename + ".xlsx", System.Text.Encoding.UTF8);
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet worksheet = pck.Workbook.Worksheets.Add(filename);
worksheet.Cells["A1"].LoadFromCollection<T>(list, true);
//--------------------------------------------Create Rtl
if (isRtl)
worksheet.View.RightToLeft = true;
//--------------------------------------------Create AutoFilter
worksheet.Cells[worksheet.Dimension.Address].AutoFilter = true;
//--------------------------------------------Create Format as table
//create a range for the table
ExcelRange range = worksheet.Cells[1, 1, worksheet.Dimension.End.Row, worksheet.Dimension.End.Column];
//add a table to the range
var tab = worksheet.Tables.Add(range, "Table1");
//format the table
tab.TableStyle = TableStyles.Medium2;
//--------------------------------------------
var ms = new System.IO.MemoryStream();
pck.SaveAs(ms);
ms.WriteTo(response.OutputStream);
response.Clear();
//response.ContentType = "application/vnd.ms-excel"; //xls
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; //xlsx
response.AddHeader("content-disposition", String.Format("attachment;filename={0}", Path.GetFileName(path)));
response.BinaryWrite(pck.GetAsByteArray());
response.Flush();
response.End();
}
注意:使用“Install-Package EPPlus”安装 EPPlus
- 使用 Microsoft.Office.Interop.Excel 的 ListToExcel 的 C# 扩展方法:
public static void ListToExcel<T>(this IList<T> list, string filename)
{
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
app.Visible = false;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
worksheet.Name = filename;
PropertyInfo[] properties = typeof(T).GetProperties();
for (int i = 0; i < properties.Length; i++)
{
worksheet.Cells[1, i + 1] = properties[i].Name;
worksheet.Cells[1, i + 1].AutoFilter();
}
for (int i = 0; i < list.Count; i++)
{
var item = list[i];
for (int j = 0; j < properties.Length; j++)
{
var prop = properties[j];
worksheet.Cells[i + 2, j + 1] = prop.GetValue(item);
}
}
var path = System.Web.HttpContext.Current.Server.MapPath("~/" + filename + ".xlsx");
if (File.Exists(path))
File.Delete(path);
worksheet.SaveAs(path);
workbook.Close();
app.Quit();
var response = HttpContext.Current.Response;
using (FileStream fs = File.OpenRead(path))
{
int length = (int)fs.Length;
byte[] buffer;
using (BinaryReader br = new BinaryReader(fs))
{
buffer = br.ReadBytes(length);
}
response.Clear();
response.Buffer = true;
//response.ContentType = "application/vnd.ms-excel"; //xls
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; //xlsx
response.AddHeader("content-disposition", String.Format("attachment;filename={0}", Path.GetFileName(path)));
response.BinaryWrite(buffer);
response.Flush();
response.End();
}
}
注意:如果您使用 Microsoft.Office.Interop.Excel,必须在客户端安装 Office。
- ListToCsv 的 C# 扩展方法:
public static void ListToCsv<T>(this IList<T> list, string filename)
{
string StringHeaders = "";
string StringRows = "";
PropertyInfo[] properties = typeof(T).GetProperties();
for (int i = 0; i < properties.Length - 1; i++)
{
StringHeaders += properties[i].Name + ",";
}
var lastPropName = properties[properties.Length - 1].Name;
StringHeaders += lastPropName + Environment.NewLine;
foreach (var item in list)
{
for (int i = 0; i < properties.Length - 1; i++)
{
var prop = properties[i];
StringRows += prop.GetValue(item) + ",";
}
var lastPropInfo = properties[properties.Length - 1];
StringRows += lastPropInfo.GetValue(item) + Environment.NewLine;
}
var response = HttpContext.Current.Response;
response.Clear();
response.AddHeader("content-disposition", "attachment; filename=" + filename + ".csv");
response.AddHeader("content-type", "text/csv");
using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
{
writer.WriteLine(StringHeaders + StringRows);
}
response.Flush();
response.End();
}