Skip to content

Instantly share code, notes, and snippets.

@jtlimson
Last active August 28, 2020 02:19
Show Gist options
  • Save jtlimson/74a7c2e8918a9cce59ab6ecd4d315c42 to your computer and use it in GitHub Desktop.
Save jtlimson/74a7c2e8918a9cce59ab6ecd4d315c42 to your computer and use it in GitHub Desktop.
using Excel = Microsoft.Office.Interop.Excel;
class Program
{
public static void Main(string[] args)
{
dynamic[] data = new dynamic[2];
data[0] = new {
ID = "1",
CODE = "1",
NAME = "Test 1",
};
data[1] = new {
ID = "2",
CODE = "2",
NAME = "Test 2",
};
data[2] = new {
ID = "3",
CODE = "3",
NAME = "Test 3",
};
GenerateGenericExcel(data) ;
}
static void GenerateGenericExcel(dynamic[] data, string filename = "test.xlsx") {
// ColumnDescriptionList Header = new ColumnDescriptionList();
Excel.Application xlApp = new Excel.Application();
if (xlApp == null || data.Length == 0)
{
return;
}
Excel.Workbook xlWorkBook = xlApp.Workbooks.Add(Type.Missing);
Excel.Worksheet xlWorkSheet = null;
xlWorkSheet = xlWorkBook.Sheets["Sheet1"];
xlWorkSheet = xlWorkBook.ActiveSheet;
//Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(Filename: @Path.Combine(rootDirectory, "Templates", "Template.xlsx"), Editable: true);
//Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets["Sheet1"];
object misValue = System.Reflection.Missing.Value;
Excel.Range cells = xlWorkBook.Worksheets[1].Cells;
cells.NumberFormat = "@";
//Create Header
int index = 1;
foreach (var prop in data[0].GetType().GetProperties())
{
// xlWorkSheet.Cells[1, index] = Header.Items[prop.Name];
xlWorkSheet.Cells[1, index] = prop.Name;
index++;
}
//Create Content
for (int i = 0, cell = 2; i < data.Length; i++, cell++)
{
var prop = data[i].GetType().GetProperties();
for (int j = 0; j < prop.Length; j++)
{
var value = data[i].GetType().GetProperty(prop[j].Name).GetValue(data[i], null);
xlWorkSheet.Cells[cell, j + 1] = value;
}
}
xlWorkSheet.Columns.AutoFit();
xlWorkBook.SaveAs(Path.Combine(saveLocation, filename), Excel.XlFileFormat.xlWorkbookDefault, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment