csharp 将数据导出为excel
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 将数据导出为excel相关的知识,希望对你有一定的参考价值。
using (ExcelPackage pck = new ExcelPackage())
{
TenantsDetailsSheet(pck, tenantList.Output);
}
private ExcelPackage TenantsDetailsSheet(ExcelPackage pck, List<GetCSPTenant.Out> annuityList)
{
var input = new GetCSPSubscription.In();
input.in_status = "A";
input.in_update_status = "N";
input.in_accountcode = annuityList.FirstOrDefault().out_accountcode;
input.in_subscription_type = annuityList.FirstOrDefault().out_tenant_type;
var getCSPSubscriptionForAccount = subAgreementApplicationService.GetCSPSubscription(input);
List<string> sheetNames = new List<string>();
string sheetName = string.Empty;
string companyName = string.Empty;
int counter = 0;
int tenantCounter = 0;
List<string> headerList = new List<string>();
#region Tenant details with all in one sheet
ExcelWorksheet detailsSheet = pck.Workbook.Worksheets.Add("DETAILS");// add a tab named DETAILS in Excel
detailsSheet.PrinterSettings.FitToWidth = 1;
detailsSheet.PrinterSettings.FitToPage = true;
detailsSheet.PrinterSettings.FitToHeight = 0;
using (ExcelRange rng = detailsSheet.Cells[detailsSheet.Cells.Start.Row, detailsSheet.Cells.Start.Column, detailsSheet.Cells.End.Row, detailsSheet.Cells.End.Column])
{
rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
rng.Style.Fill.BackgroundColor.SetColor(Color.White);
}
headerList.Add("TENANT ID");
headerList.Add("TENANT NAME");
headerList.Add("MPN ID");
headerList.Add("SKU");
headerList.Add("REFERENCE");
headerList.Add("QTY");
headerList.Add("CHARGE TYPE");
headerList.Add("STATUS");
headerList.Add("START USAGE");
headerList.Add("END USAGE");
headerList.Add("REVALUATION PERIOD");
headerList.Add("UNIT PRICE");
headerList.Add("LINE AMOUNT");
headerList.Add("UNIT RRP");
headerList.Add("LINE RRP");
detailsSheet.Column(1).Width = 30; // A TENANT ID
detailsSheet.Column(2).Width = 30; // A TENANT NAME
detailsSheet.Column(3).Width = 30; // A MPN ID
detailsSheet.Column(4).Width = 45; // B SKU
detailsSheet.Column(5).Width = 30; // C REFERENCE
detailsSheet.Column(6).Width = 20; // D QTY
detailsSheet.Column(7).Width = 20; // E CHARGE TYPE
detailsSheet.Column(8).Width = 20; // F STATUS
detailsSheet.Column(9).Width = 20; // G START DATE
detailsSheet.Column(10).Width = 20; // G EXPIRE DATE
detailsSheet.Column(11).Width = 20; // G REVALUATION DATE
detailsSheet.Column(12).Width = 20; // G UNIT PRICE
detailsSheet.Column(13).Width = 20; // G TOTAL AMOUNT
detailsSheet.Column(14).Width = 20; // G UNIT RRP
detailsSheet.Column(15).Width = 20; // G TOTAL RRP
// Image Row Height
detailsSheet.Row(1).Height = 80;
// Add Dicker Logo
_excelManager.AddImage(detailsSheet, 1, 1, Global.CurrentUrl + "images/newsletter/DickerData-Logo.jpg", 160, 90);
// Add Contact Banner
if (Global.CompanyCode == Global.NZ)
{
_excelManager.AddImage(detailsSheet, 1, 2, Global.CurrentUrl + "images/newsletter/contact-banner-nz.png", 813, 90);
}
else
{
_excelManager.AddImage(detailsSheet, 1, 2, Global.CurrentUrl + "images/newsletter/contact-banner.png", 813, 90);
}
int detailSheetrowCounter = 3;
char cellPosition = 'A';
var tableStartRow = detailSheetrowCounter;
foreach (var header in headerList)
{
detailsSheet.Cells[cellPosition.ToString() + detailSheetrowCounter].Value = header;
cellPosition++;
}
cellPosition--;
// Format Column Titles
using (ExcelRange rng = detailsSheet.Cells["A3:" + (cellPosition).ToString() + "3"])
{
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
rng.Style.Fill.BackgroundColor.SetColor(Color.Maroon);
rng.Style.Font.Color.SetColor(Color.White);
}
detailSheetrowCounter++;
foreach (var item in getCSPSubscriptionForAccount.Output.OrderBy(x => x.out_company_name).ThenBy(x => x.out_parent_subscription))
{
decimal qty = 0;
decimal amount = 0;
string status = item.out_status_desc;
if (item.out_status != "XX" &&
(getCSPSubscriptionForAccount.Output.Where(x => x.out_subscription_id == item.out_parent_subscription).FirstOrDefault().out_status != "XX"))
{
qty = decimal.Parse(item.out_qty);
amount = decimal.Parse(item.out_amount);
}
else
{
status = "Suspended";
}
detailsSheet.Cells["A" + detailSheetrowCounter].Value = item.out_tenant_id;
detailsSheet.Cells["B" + detailSheetrowCounter].Value = item.out_company_name;
detailsSheet.Cells["C" + detailSheetrowCounter].Value = item.out_mpnid;
detailsSheet.Cells["D" + detailSheetrowCounter].Value = item.out_stk_description;
detailsSheet.Cells["E" + detailSheetrowCounter].Value = item.out_sub_description;
detailsSheet.Cells["F" + detailSheetrowCounter].Value = qty;
detailsSheet.Cells["G" + detailSheetrowCounter].Value = item.out_charge_type;
detailsSheet.Cells["H" + detailSheetrowCounter].Value = status;
detailsSheet.Cells["I" + detailSheetrowCounter].Value = item.out_start_usage;
detailsSheet.Cells["J" + detailSheetrowCounter].Value = item.out_end_usage;
detailsSheet.Cells["K" + detailSheetrowCounter].Value = item.out_expiry_date;
detailsSheet.Cells["L" + detailSheetrowCounter].Value = Decimal.Parse(item.out_price).ToString("C");
detailsSheet.Cells["M" + detailSheetrowCounter].Value = amount.ToString("C");
detailsSheet.Cells["N" + detailSheetrowCounter].Value = Decimal.Parse(item.out_rrp).ToString("C");
detailsSheet.Cells["O" + detailSheetrowCounter].Value = (Decimal.Parse(item.out_rrp) * qty).ToString("C");
detailSheetrowCounter++;
}
detailSheetrowCounter++;
detailsSheet.Cells["L" + detailSheetrowCounter].Value = "TOTAL:";
detailsSheet.Cells["L" + detailSheetrowCounter].Style.Font.Bold = true;
detailsSheet.Cells["L" + tableStartRow + ":L" + detailSheetrowCounter].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
detailsSheet.Cells["M" + detailSheetrowCounter].Value = getCSPSubscriptionForAccount.Output.Sum(x => Decimal.Parse(x.out_amount)).ToString("C");
detailsSheet.Cells["M" + detailSheetrowCounter].Style.Font.Bold = true;
detailsSheet.Cells["M" + tableStartRow + ":M" + detailSheetrowCounter].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
#endregion
foreach (var tenant in annuityList.OrderBy(x => x.out_company_name))
{
#region headers
companyName = string.IsNullOrEmpty(tenant.out_company_name) ? "<NO END USER NAME>" : tenant.out_company_name;
sheetName = companyName;
tenantCounter++;
if (sheetNames.Where(x => x == sheetName.ToUpper()).Count() > 0)
{
counter = sheetNames.Where(x => x == sheetName.ToUpper()).Count();
sheetName = sheetName + " (" + counter + ")";
counter = 0;
}
sheetNames.Add(companyName.ToUpper());
ExcelWorksheet ws = pck.Workbook.Worksheets.Add(sheetName);
ws.PrinterSettings.FitToWidth = 1;
ws.PrinterSettings.FitToPage = true;
ws.PrinterSettings.FitToHeight = 0;
using (ExcelRange rng = ws.Cells[ws.Cells.Start.Row, ws.Cells.Start.Column, ws.Cells.End.Row, ws.Cells.End.Column])
{
rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
rng.Style.Fill.BackgroundColor.SetColor(Color.White);
}
// Create Headers
headerList = new List<string>();
headerList.Add("MPN ID");
headerList.Add("SKU");
headerList.Add("REFERENCE");
headerList.Add("QTY");
headerList.Add("CHARGE TYPE");
headerList.Add("STATUS");
headerList.Add("START USAGE");
headerList.Add("END USAGE");
headerList.Add("REVALUATION PERIOD");
headerList.Add("UNIT PRICE");
headerList.Add("LINE AMOUNT");
headerList.Add("UNIT RRP");
headerList.Add("LINE RRP");
// Capture Number Of Columns
// We'll Use This Later When Creating Rows
int iColCount = headerList.Count;
ws.Column(1).Width = 30; // A MPN ID
ws.Column(2).Width = 45; // B SKU
ws.Column(3).Width = 30; // C REFERENCE
ws.Column(4).Width = 20; // D QTY
ws.Column(5).Width = 20; // E CHARGE TYPE
ws.Column(6).Width = 20; // F STATUS
ws.Column(7).Width = 20; // G START DATE
ws.Column(8).Width = 20; // G EXPIRE DATE
ws.Column(9).Width = 20; // G EXPIRE DATE
ws.Column(10).Width = 20; // G UNIT PRICE
ws.Column(11).Width = 20; // G TOTAL AMOUNT
ws.Column(12).Width = 20; // G UNIT PRICE
ws.Column(13).Width = 20; // G TOTAL AMOUNT
// Image Row Height
ws.Row(1).Height = 80;
// Add Dicker Logo
//AddImage(ws, 1, 1, Globals.CurrentUrl + "images/DickerData_Logo_BlackRed.png", 160, 90);
_excelManager.AddImage(ws, 1, 1, Global.CurrentUrl + "images/newsletter/DickerData-Logo.jpg", 160, 90);
// Add Contact Banner
if (Global.CompanyCode == Global.NZ)
{
_excelManager.AddImage(ws, 1, 2, Global.CurrentUrl + "images/newsletter/contact-banner-nz.png", 813, 90);
}
else
{
_excelManager.AddImage(ws, 1, 2, Global.CurrentUrl + "images/newsletter/contact-banner.png", 813, 90);
}
int rowCounter = 3;
#endregion
#region annuities details
rowCounter++;
ws.Cells["A" + rowCounter].Style.Font.UnderLine = true;
ws.Cells["A" + rowCounter].Style.Font.Color.SetColor(Color.Blue);
ws.Cells["A" + rowCounter].Hyperlink = new ExcelHyperLink("SUMMARY" + "!A" + (tenantCounter + 3), "Return to Summary Page");
rowCounter++;
rowCounter++;
int orderStartRow = 0;
var annuityTypeDetails = _dbManager.GetAnnuityTypeDetails();
//annuityList = annuityList.Where(x => "active".Equals(x.out_status.ToLower())).ToList();
//foreach (var annuity in annuityList)
//{
var annuityTypeInfo = annuityTypeDetails.Where(x => x.CompanyCode == Global.CompanyCode && x.ProgramType == tenant.out_tenant_type).FirstOrDefault();
if (annuityTypeInfo == null) continue;
orderStartRow = rowCounter;
#region order headers
ws.Cells["A" + rowCounter].Value = "END USER";
ws.Cells["B" + rowCounter].Value = tenant.out_company_name;
ws.Cells["B" + rowCounter].Style.Font.Bold = true;
ws.Cells["D" + rowCounter].Value = "STATUS";
ws.Cells["E" + rowCounter].Value = tenant.out_status_desc;
ws.Cells["E" + rowCounter].Style.Font.Bold = true;
rowCounter++;
rowCounter += 2;
#endregion
// write table header
cellPosition = 'A';
tableStartRow = rowCounter;
foreach (var header in headerList)
{
ws.Cells[cellPosition.ToString() + rowCounter].Value = header;
cellPosition++;
}
cellPosition--;
rowCounter++;
var getOrderItemDetailsResult = getCSPSubscriptionForAccount.Output.Where(x => x.out_tenant_id == tenant.out_tenant_id).ToList();
foreach (var item in getOrderItemDetailsResult.OrderBy(x => x.out_parent_subscription))
{
decimal qty = 0;
decimal amount = 0;
string status = item.out_status_desc;
if (item.out_status != "XX" &&
(getCSPSubscriptionForAccount.Output.Where(x => x.out_subscription_id == item.out_parent_subscription).FirstOrDefault().out_status != "XX"))
{
qty = decimal.Parse(item.out_qty);
amount = decimal.Parse(item.out_amount);
}
else
{
status = "Suspended";
}
ws.Cells["A" + rowCounter].Value = item.out_mpnid;
ws.Cells["B" + rowCounter].Value = item.out_stk_description;
ws.Cells["C" + rowCounter].Value = item.out_sub_description;
ws.Cells["D" + rowCounter].Value = qty;
ws.Cells["E" + rowCounter].Value = item.out_charge_type;
ws.Cells["F" + rowCounter].Value = status;
ws.Cells["G" + rowCounter].Value = item.out_start_usage;
ws.Cells["H" + rowCounter].Value = item.out_end_usage;
ws.Cells["I" + rowCounter].Value = item.out_expiry_date;
ws.Cells["J" + rowCounter].Value = Decimal.Parse(item.out_price).ToString("C");
ws.Cells["K" + rowCounter].Value = amount.ToString("C");
ws.Cells["L" + rowCounter].Value = Decimal.Parse(item.out_rrp).ToString("C");
ws.Cells["M" + rowCounter].Value = (Decimal.Parse(item.out_rrp) * qty).ToString("C");
rowCounter++;
}
ws.Cells["C" + tableStartRow + ":C" + rowCounter].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
rowCounter++;
if (string.IsNullOrEmpty(tenant.out_amount))
tenant.out_amount = "0";
ws.Cells["J" + rowCounter].Value = "TOTAL:";
ws.Cells["J" + rowCounter].Style.Font.Bold = true;
ws.Cells["J" + tableStartRow + ":J" + rowCounter].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
ws.Cells["K" + rowCounter].Value = Decimal.Parse(tenant.out_amount).ToString("C");
ws.Cells["K" + rowCounter].Style.Font.Bold = true;
ws.Cells["K" + tableStartRow + ":K" + rowCounter].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
ws.Cells["L" + tableStartRow + ":L" + rowCounter].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
ws.Cells["M" + tableStartRow + ":M" + rowCounter].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
// Format Background color
using (ExcelRange rng = ws.Cells["A" + orderStartRow + ":" + (cellPosition).ToString() + rowCounter])
{
rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
rng.Style.Fill.BackgroundColor.SetColor(Color.LightGray);
}
using (ExcelRange rng = ws.Cells["A" + tableStartRow + ":" + (cellPosition).ToString() + tableStartRow])
{
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
rng.Style.Fill.BackgroundColor.SetColor(Color.Maroon);
rng.Style.Font.Color.SetColor(Color.White);
}
rowCounter += 2;
if (getOrderItemDetailsResult == null || getOrderItemDetailsResult.Count == 0)
{
using (var rng = ws.Cells["A" + rowCounter + ":K" + rowCounter])
{
rng.Merge = true;
}
rowCounter += 2;
}
#endregion
}
return pck;
}
public void AddImage(ExcelWorksheet ws, int rowIndex, int colIndex, String imageFile = "", int iWidth = 0, int iHeight = 0)
{
// Exit If Image Is Empty
if (string.IsNullOrEmpty(imageFile))
return;
// Create Are Image Handles
ExcelPicture picture;
Image image;
// Source Image File From URL
var request = WebRequest.Create(imageFile);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
using (var response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
image = Bitmap.FromStream(stream);
}
}
// If Image Exists
// Insert into Excel
if (image != null)
{
string uniqueId = DateTime.Now.Ticks.ToString();
try
{
picture = ws.Drawings.AddPicture("pic" + uniqueId, image);
picture.SetPosition(rowIndex - 1, 5, colIndex - 1, 15);
picture.SetSize(iWidth, iHeight);
}
catch (Exception ex)
{
_dickerDataLogger.Add(LogType.Downloads, "Export", "ExportAllCartsToExcel", ex.Message, _currentUser.AccountId, _currentUser.LoginId);
}
}
}
以上是关于csharp 将数据导出为excel的主要内容,如果未能解决你的问题,请参考以下文章