Introducción a Excel en C #

En el mundo moderno del desarrollo de aplicaciones, a menudo es necesario trabajar con documentos de Excel. La mayoría de las veces se trata de varios tipos de informes, pero a veces se utilizan archivos xls / x como almacenamiento de datos. Por ejemplo, si un usuario necesita poder cargar datos en una aplicación o cargarlos en un formato legible por humanos, Excel es el estándar de facto. Interfaz relativamente amigable, estructura transparente, junto con su prevalencia ... es difícil nombrar una mejor solución de inmediato.

Sin embargo, muchas personas todavía asocian Excel con algo pesado, torpe y complejo. Veamos cómo nosotros, los desarrolladores normales de C #, podemos generar fácilmente un documento de Excel simple usando un informe tabular como ejemplo.

Referencia histórica

Los días en los que dominaba el .xls (formato de archivo binario de Excel) han quedado atrás y ahora solo tenemos .xlsx (libro de trabajo de Excel), dentro de Office Open XML. Este último es un archivo .zip normal con archivos XML. No profundizaremos en su estructura, espero sinceramente que nunca lo necesites.

github, , , . EPPlus. , Excel, EPPlus. 4 , 5‐ .

, , - ,  Excel - 100500%. - - — .

, . — . — , . , - backend- - , id . , id , .

, ,   - " excel MarketReport". , , — :

EPPlus 4.5.3.3 .

Generate. ExcelPackage ,   . .

main , Excel . .

, exception:InvalidOperationException: The workbook must contain at least one worksheet

, Excel , . , :

var sheet = package.Workbook.Worksheets    
		.Add("Market Report");

... ! , , 2,5KB - Excel .

. Cells . , , - :

sheet.Cells["B2"].Value = "Company:";
sheet.Cells[2, 3].Value = report.Company.Name;
.
sheet.Cells["B2"].Value = "Company:";
sheet.Cells[2, 3].Value = report.Company.Name;
sheet.Cells["B3"].Value = "Location:";
sheet.Cells["C3"].Value = $"{report.Company.Address}, " +
  												$"{report.Company.City}, " +                          
  												$"{report.Company.Country}";
sheet.Cells["B4"].Value = "Sector:";
sheet.Cells["C4"].Value = report.Company.Sector;
sheet.Cells["B5"].Value = report.Company.Description;

History:

sheet.Cells[8, 2, 8, 4].LoadFromArrays(new object[][]{ new []{"Capitalization", "SharePrice", "Date"} });
var row = 9;
var column = 2;
foreach (var item in report.History)
{
  sheet.Cells[row, column].Value = item.Capitalization;
  sheet.Cells[row, column + 1].Value = item.SharePrice;
  sheet.Cells[row, column + 2].Value = item.Date;    
  row++;
}

LoadFromArrays, () . , object EPPlus ToString, .

, , .

-, , - ... ,  , " - " - .

, , , , , ... , backend , Excel Sheet!

. — , — . ?

- Excel, , . , ... , :

sheet.Cells[1, 1, row, column + 2].AutoFitColumns();
sheet.Column(2).Width = 14;
sheet.Column(3).Width = 12;

, Style. 3- . , ...

sheet.Cells[9, 4, 9 + report.History.Length, 4].Style.Numberformat.Format = "yyyy";
sheet.Cells[9, 2, 9 + report.History.Length, 2].Style.Numberformat.Format =  "### ### ### ##0";

, . , EPPlus, — ExcelRange, , 1 .

sheet.Column(2).Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
sheet.Cells[8, 3, 8 + report.History.Length, 3].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;

, Style.Font, , , 2- , , Excel:

sheet.Cells[8, 2, 8, 4].Style.Font.Bold = true;
sheet.Cells["B2:C4"].Style.Font.Bold = true;

, . - - , ... ?

sheet.Cells[8, 2, 8 + report.History.Length, 4].Style.Border.BorderAround(ExcelBorderStyle.Double);
sheet.Cells[8, 2, 8, 4].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;

" , , ?" - , , 9-...

, EPPlus API. , :

var capitalizationChart = sheet.Drawings.AddChart("FindingsChart", OfficeOpenXml.Drawing.Chart.eChartType.Line);
capitalizationChart.Title.Text = "Capitalization";
capitalizationChart.SetPosition(7, 0, 5, 0);
capitalizationChart.SetSize(800, 400);
var capitalizationData = (ExcelChartSerie)(capitalizationChart.Series.Add(sheet.Cells["B9:B28"], sheet.Cells["D9:D28"]));
capitalizationData.Header = report.Company.Currency;

, :

sheet.Protection.IsProtected = true;

,   .

¿Qué dice la versión final del método Generate?
public byte[] Generate(MarketReport report)
{    
  var package = new ExcelPackage();    
  
  var sheet = package.Workbook.Worksheets        
    	.Add("Market Report");      
  
  sheet.Cells["B2"].Value = "Company:";    
  sheet.Cells[2, 3].Value = report.Company.Name;    
  sheet.Cells["B3"].Value = "Location:";    
  sheet.Cells["C3"].Value = $"{report.Company.Address}, " +
    												$"{report.Company.City}, " +                             
    												$"{report.Company.Country}";    
  sheet.Cells["B4"].Value = "Sector:";    
  sheet.Cells["C4"].Value = report.Company.Sector;    
  sheet.Cells["B5"].Value = report.Company.Description;    
  
  sheet.Cells[8, 2, 8, 4].LoadFromArrays(new object[][]{ new []{"Capitalization", "SharePrice", "Date"} });    
  var row = 9;    
  var column = 2;    
  foreach (var item in report.History)    
  {        
    	sheet.Cells[row, column].Value = item.Capitalization;        
   		sheet.Cells[row, column + 1].Value = item.SharePrice;        
   		sheet.Cells[row, column + 2].Value = item.Date;        
    	row++;    
  }    
  
  sheet.Cells[1, 1, row, column + 2].AutoFitColumns();    
  sheet.Column(2).Width = 14;    
  sheet.Column(3).Width = 12;        
  
  sheet.Cells[9, 4, 9+ report.History.Length, 4].Style.Numberformat.Format = "yyyy";    
  sheet.Cells[9, 2, 9+ report.History.Length, 2].Style.Numberformat.Format =  "### ### ### ##0";    
  
  sheet.Column(2).Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;    
  sheet.Cells[8, 3, 8 + report.History.Length, 3].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;    
  sheet.Column(4).Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;    
  
  sheet.Cells[8, 2, 8, 4].Style.Font.Bold = true;    
  sheet.Cells["B2:C4"].Style.Font.Bold = true;
  
  sheet.Cells[8, 2, 8 + report.History.Length, 4].Style.Border.BorderAround(ExcelBorderStyle.Double);    
  sheet.Cells[8, 2, 8, 4].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;     
  
  var capitalizationChart = sheet.Drawings.AddChart("FindingsChart", OfficeOpenXml.Drawing.Chart.eChartType.Line);    
  capitalizationChart.Title.Text = "Capitalization";    
  capitalizationChart.SetPosition(7, 0, 5, 0);    
  capitalizationChart.SetSize(800, 400);    
  var capitalizationData = (ExcelChartSerie)(capitalizationChart.Series.Add(sheet.Cells["B9:B28"], sheet.Cells["D9:D28"]));    
  capitalizationData.Header = report.Company.Currency;       
  
  sheet.Protection.IsProtected = true;    
  
  return package.GetAsByteArray();
}

En primer lugar, en primer lugar, que hemos hecho frente con éxito a la tarea, es decir, hemos generado nuestro primer informe de Excel , hemos trabajado con estilos e incluso hemos resuelto un par de problemas relacionados.

En segundo lugar, puede tener sentido buscar un nuevo trabajo, pero, de cara al futuro , no tendría prisa con esto ... Si esta publicación obtiene más de 1 vistas, en la segunda parte hablaremos sobre cómo puede separar el estilo de la lógica de llenado de datos. , simplifica las manipulaciones de las celdas y, en general, hace que el código sea más fácil de mantener.




All Articles