csharp EPPlus工作表格式(使用http://epplus.codeplex.com/)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp EPPlus工作表格式(使用http://epplus.codeplex.com/)相关的知识,希望对你有一定的参考价值。

using System.Text;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using OfficeOpenXml.Table;
using System.Drawing;
using System.Data;

public partial class Sample: Page
{
	protected void GenerateSpreadsheet(object sender, EventArgs e)
	{
		using (ExcelPackage pck = new ExcelPackage())
		{
			// date columns
			List<string> dateColumns = new List<string>() {

				"DateAdded",
				"SentDate"
			};
			
			// hide columns
			List<string> hideColumns = new List<string>() {

				"RecordID",
				"CategoryID"
			};
			
			DataTable table = GetTable();
			ExcelWorksheet ws = pck.Workbook.Worksheets.Add("MyTable");
			ws.Cells["A1"].LoadFromDataTable(table, true, TableStyles.Medium6);

			FormatWorksheetData(dateColumns, hideColumns, table, ws);
			
			// make sure it is sent as a XLSX file
			Response.ContentType = "application/vnd.ms-excel";
			// make sure it is downloaded rather than viewed in the browser window
			Response.AddHeader("Content-disposition", "attachment; filename=myworksheet.xlsx");
			Response.BinaryWrite(pck.GetAsByteArray());
			Response.End();
		}
	}
	
	private DateTable GetTable()
	{
		// code to retrieve data and return a DataTable
	}

	private static void FormatWorksheetData(List<string> dateColumns, List<string> hideColumns, DataTable table, ExcelWorksheet ws)
	{
		int columnCount = table.Columns.Count;
		int rowCount = table.Rows.Count;

		ExcelRange r;

		// which columns have dates in
		for (int i = 1; i <= columnCount; i++)
		{
			// if cell header value matches a date column
			if (dateColumns.Contains(ws.Cells[1, i].Value.ToString()))
			{
				r = ws.Cells[2, i, rowCount + 1, i];
				r.AutoFitColumns();
				r.Style.Numberformat.Format = @"dd MMM yyyy hh:mm";
			}
		}
		// get all data and autofit
		r = ws.Cells[1, 1, rowCount + 1, columnCount];
		r.AutoFitColumns();

		// which columns have columns that should be hidden
		for (int i = 1; i <= columnCount; i++)
		{
			// if cell header value matches a hidden column
			if (hideColumns.Contains(ws.Cells[1, i].Value.ToString()))
			{
				ws.Column(i).Hidden = true;
			}
		}
	}
}

以上是关于csharp EPPlus工作表格式(使用http://epplus.codeplex.com/)的主要内容,如果未能解决你的问题,请参考以下文章

如何在C#中使用EPPlus设置xlsx单元格宽度

使用epplus c#设置Excel工作表单元格的自定义BackgroundColor

csharp EPPlusの基本的な使い方メモ

EPPlus 表@列参考

EPPlus 编号格式

EPPlus 在 DataField 上排序数据透视表,而不仅仅是 RowField