【发布时间】:2021-05-07 01:04:49
【问题描述】:
有人可以提供一个链接,其中包含有关在 asp.net Web 应用程序中使用 c# 将数据导出到 excel 文件的教程。我搜索了互联网,但没有找到任何可以解释他们如何做到这一点的教程。
【问题讨论】:
标签: c# asp.net export-to-excel
有人可以提供一个链接,其中包含有关在 asp.net Web 应用程序中使用 c# 将数据导出到 excel 文件的教程。我搜索了互联网,但没有找到任何可以解释他们如何做到这一点的教程。
【问题讨论】:
标签: c# asp.net export-to-excel
或者,如果您不想在网络服务器上安装 Microsoft Office
我推荐使用CarlosAg.ExcelXmlWriter,可以在这里找到:http://www.carlosag.net/tools/excelxmlwriter/
ExcelXmlWriter 的代码示例:
using CarlosAg.ExcelXmlWriter;
class TestApp {
static void Main(string[] args) {
Workbook book = new Workbook();
Worksheet sheet = book.Worksheets.Add("Sample");
WorksheetRow row = sheet.Table.Rows.Add();
row.Cells.Add("Hello World");
book.Save(@"c:\test.xls");
}
}
【讨论】:
有一个简单的方法来使用npoi.mapper,只需不到 2 行
var mapper = new Mapper();
mapper.Save("test.xlsx", objects, "newSheet");
【讨论】:
将 List 传递给下面的方法,它将列表转换为缓冲区,然后返回缓冲区,将下载一个文件。
List<T> resultList = New List<T>();
byte[] buffer = Write(resultList, true, "AttendenceSummary");
return File(buffer, "application/excel", reportTitle + ".xlsx");
public static byte[] Write<T>(IEnumerable<T> list, bool xlsxExtension = true, string sheetName = "ExportData")
{
if (list == null)
{
throw new ArgumentNullException("list");
}
XSSFWorkbook hssfworkbook = new XSSFWorkbook();
int Rowspersheet = 15000;
int TotalRows = list.Count();
int TotalSheets = TotalRows / Rowspersheet;
for (int i = 0; i <= TotalSheets; i++)
{
ISheet sheet1 = hssfworkbook.CreateSheet(sheetName + "_" + i);
IRow row = sheet1.CreateRow(0);
int index = 0;
foreach (PropertyInfo property in typeof(T).GetProperties())
{
ICellStyle cellStyle = hssfworkbook.CreateCellStyle();
IFont cellFont = hssfworkbook.CreateFont();
cellFont.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
cellStyle.SetFont(cellFont);
ICell cell = row.CreateCell(index++);
cell.CellStyle = cellStyle;
cell.SetCellValue(property.Name);
}
int rowIndex = 1;
// int rowIndex2 = 1;
foreach (T obj in list.Skip(Rowspersheet * i).Take(Rowspersheet))
{
row = sheet1.CreateRow(rowIndex++);
index = 0;
foreach (PropertyInfo property in typeof(T).GetProperties())
{
ICell cell = row.CreateCell(index++);
cell.SetCellValue(Convert.ToString(property.GetValue(obj)));
}
}
}
MemoryStream file = new MemoryStream();
hssfworkbook.Write(file);
return file.ToArray();
}
【讨论】:
我编写了一个 C# 类,它允许您使用 OpenXML 库将 DataSet、DataTable 或 List 数据直接写入 Excel .xlsx 文件。
http://mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm
它完全免费下载,并且非常对 ASP.Net 友好。
只需将要写入的数据、要创建的文件的名称和页面的“响应”变量传递给我的 C# 函数,它就会为您创建 Excel 文件,并将其直接写入页面,准备好供用户保存/打开。
class Employee;
List<Employee> listOfEmployees = new List<Employee>();
// The following ASP.Net code gets run when I click on my "Export to Excel" button.
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
// It doesn't get much easier than this...
CreateExcelFile.CreateExcelDocument(listOfEmployees, "Employees.xlsx", Response);
}
(我在一家金融公司工作,如果我们的每个应用都没有这个功能,我们就会迷失方向!!)
【讨论】: