Recentemente precisei criar uma função para exportar dados para uma planilha do Excel e enviar para o usuário através de download.
O approach padrão para isso é a utilização dos Web Office Componentes, no entanto, isso exige a intervenção no servidor, além de não ser muito amigável.
Claro que um código de exportação envolverá mais linhas, o que poderá tornar a tarefa um pouco chata. Para isso, CarlosAG criou uma ferramenta muito prática.Você monta no Excel sua planilha com a formatação que quiser e salva ela como XML Spreedsheet. Depois, abre o xml no Excel Xml Writer Library Code Generator e ele gera para você o código do layout em C#.
Um exemplo de código gerado é o abaixo:
1: namespace ExcelXmlWriter.Sample {
2: using System;
3: using System.Xml;
4: using CarlosAg.ExcelXmlWriter;
5:
6:
7: public class App {
8:
9: public void Generate(string filename) {
10: Workbook book = new Workbook();
11: // -----------------------------------------------
12: // Properties
13: // -----------------------------------------------
14: book.Properties.Author = "Cássio Rogério Eskelsen";
15: book.Properties.LastAuthor = "Cássio Rogério Eskelsen";
16: book.Properties.Created = new System.DateTime(2008, 2, 11, 9, 28, 37, 0);
17: book.Properties.Company = "simple";
18: book.Properties.Version = "12.00";
19: book.ExcelWorkbook.WindowHeight = 11985;
20: book.ExcelWorkbook.WindowWidth = 19095;
21: book.ExcelWorkbook.WindowTopX = 120;
22: book.ExcelWorkbook.WindowTopY = 45;
23: book.ExcelWorkbook.ProtectWindows = false;
24: book.ExcelWorkbook.ProtectStructure = false;
25: // -----------------------------------------------
26: // Generate Styles
27: // -----------------------------------------------
28: this.GenerateStyles(book.Styles);
29: // -----------------------------------------------
30: // Generate Plan1 Worksheet
31: // -----------------------------------------------
32: this.GenerateWorksheetPlan1(book.Worksheets);
33: book.Save(filename);
34: }
35:
36: private void GenerateStyles(WorksheetStyleCollection styles) {
37: // -----------------------------------------------
38: // Default
39: // -----------------------------------------------
40: WorksheetStyle Default = styles.Add("Default");
41: Default.Name = "Normal";
42: Default.Font.FontName = "Calibri";
43: Default.Font.Size = 11;
44: Default.Font.Color = "#000000";
45: Default.Alignment.Vertical = StyleVerticalAlignment.Bottom;
46: // -----------------------------------------------
47: // s67
48: // -----------------------------------------------
49: WorksheetStyle s67 = styles.Add("s67");
50: s67.Name = "Hyperlink";
51: s67.Font.Underline = UnderlineStyle.Single;
52: s67.Font.FontName = "Calibri";
53: s67.Font.Size = 11;
54: s67.Font.Color = "#0000FF";
55: // -----------------------------------------------
56: // s71
57: // -----------------------------------------------
58: WorksheetStyle s71 = styles.Add("s71");
59: s71.Parent = "s67";
60: s71.Alignment.Vertical = StyleVerticalAlignment.Bottom;
61: s71.NumberFormat = "dd/mm/yy;@";
62: // -----------------------------------------------
63: // s72
64: // -----------------------------------------------
65: WorksheetStyle s72 = styles.Add("s72");
66: s72.NumberFormat = "dd/mm/yy;@";
67: // -----------------------------------------------
68: // s74
69: // -----------------------------------------------
70: WorksheetStyle s74 = styles.Add("s74");
71: s74.Alignment.Horizontal = StyleHorizontalAlignment.Right;
72: s74.Alignment.Vertical = StyleVerticalAlignment.Bottom;
73: s74.NumberFormat = "\"R$\"\\ #,##0.00;[Red]\"R$\"\\ #,##0.00";
74: }
75:
76: private void GenerateWorksheetPlan1(WorksheetCollection sheets) {
77: Worksheet sheet = sheets.Add("Plan1");
78: sheet.Table.DefaultRowHeight = 15F;
79: sheet.Table.ExpandedColumnCount = 3;
80: sheet.Table.ExpandedRowCount = 5;
81: sheet.Table.FullColumns = 1;
82: sheet.Table.FullRows = 1;
83: WorksheetColumn column0 = sheet.Table.Columns.Add();
84: column0.StyleID = "s72";
85: sheet.Table.Columns.Add(138);
86: sheet.Table.Columns.Add(89);
87: // -----------------------------------------------
88: WorksheetRow Row0 = sheet.Table.Rows.Add();
89: WorksheetCell cell;
90: cell = Row0.Cells.Add();
91: cell.StyleID = "s71";
92: cell.Data.Type = DataType.String;
93: cell.Data.Text = "www.canesh.com";
94: cell.HRef = "http://www.canesh.com/";
95: // -----------------------------------------------
96: WorksheetRow Row1 = sheet.Table.Rows.Add();
97: Row1.Index = 3;
98: cell = Row1.Cells.Add();
99: cell.Data.Type = DataType.String;
100: cell.Data.Text = "Data";
101: cell = Row1.Cells.Add();
102: cell.Data.Type = DataType.String;
103: cell.Data.Text = "Cliente";
104: cell = Row1.Cells.Add();
105: cell.Data.Type = DataType.String;
106: cell.Data.Text = "Valor a Receber";
107: // -----------------------------------------------
108: WorksheetRow Row2 = sheet.Table.Rows.Add();
109: cell = Row2.Cells.Add();
110: cell.Data.Type = DataType.DateTime;
111: cell.Data.Text = "2008-01-01T00:00:00.000";
112: cell = Row2.Cells.Add();
113: cell.Data.Type = DataType.String;
114: cell.Data.Text = "Fulano";
115: Row2.Cells.Add("123", DataType.Number, "s74");
116: // -----------------------------------------------
117: WorksheetRow Row3 = sheet.Table.Rows.Add();
118: cell = Row3.Cells.Add();
119: cell.Data.Type = DataType.DateTime;
120: cell.Data.Text = "2008-01-01T00:00:00.000";
121: cell = Row3.Cells.Add();
122: cell.Data.Type = DataType.String;
123: cell.Data.Text = "Beltrano";
124: cell = Row3.Cells.Add();
125: cell.Data.Type = DataType.Number;
126: cell.Data.Text = "2323";
127: // -----------------------------------------------
128: // Options
129: // -----------------------------------------------
130: sheet.Options.Selected = true;
131: sheet.Options.ProtectObjects = false;
132: sheet.Options.ProtectScenarios = false;
133: sheet.Options.PageSetup.Header.Margin = 0.3149606F;
134: sheet.Options.PageSetup.Footer.Margin = 0.3149606F;
135: sheet.Options.PageSetup.PageMargins.Bottom = 0.7874016F;
136: sheet.Options.PageSetup.PageMargins.Left = 0.511811F;
137: sheet.Options.PageSetup.PageMargins.Right = 0.511811F;
138: sheet.Options.PageSetup.PageMargins.Top = 0.7874016F;
139: sheet.Options.Print.PaperSizeIndex = 9;
140: sheet.Options.Print.ValidPrinterInfo = true;
141: }
142:
143:
144: }
145: }
Perceba que foram incluídas informações sobre os esilos das células.
Campos especiais necessitam de uma atenção. Se você formatou no layout um campo como DATA e/ou Valor, você deve exportar os dados no formato requerido pelo XML spreedsheet. No caso das datas, perceba que a data foi exportada como "2008-01-01T00:00:00.000" (linhas 111 e 120). Já no caso dos valores, o formato deve ser o americano (ponto separando as decimais).
Para facilitar, incluo abaixo duas rotinas auxiliares, que deixam os dados no formato requerido: