c generates excel sample sql database export excel
- 2020-06-01 10:53:34
- OfStack
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Excel;
using System.Reflection;
namespace ListToExcel
{
class Program
{
static List<objtype> objs = new List<objtype>();
static void Main(string[] args)
{
objs.Add(new objtype() { name = "allen", val = "aaa" });
objs.Add(new objtype() { name = "allen", val = "aaa" });
objs.Add(new objtype() { name = "allen", val = "aaa" });
objs.Add(new objtype() { name = "allen", val = "aaa" });
objs.Add(new objtype() { name = "allen", val = "aaa" });
objs.Add(new objtype() { name = "allen", val = "aaa" });
objs.Add(new objtype() { name = "allen", val = "aaa" });
objs.Add(new objtype() { name = "allen", val = "aaa" });
objs.Add(new objtype() { name = "allen", val = "aaa" });
objs.Add(new objtype() { name = "allen", val = "aaa" });
objs.Add(new objtype() { name = "allen", val = "aaa" });
objs.Add(new objtype() { name = "allen", val = "aaa" });
ExportDataToExcel("", "", @"c:\a.xls", "a");
}
/// <summary>
/// Export data directly to excel
/// </summary>
/// <param name="connectionString"> Concatenation string </param>
/// <param name="sql"> The query </param>
/// <param name="fileName"> The file name </param>
/// <param name="sheetName"> The name of the table </param>
static void ExportDataToExcel(string connectionString, string sql, string fileName, string sheetName)
{
Application app = new Application();
Workbook wb = app.Workbooks.Add(Missing.Value);
Worksheet ws = wb.Worksheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value) as Worksheet;
ws.Name = sheetName;
try
{
int n = 0;
for (int i = 1; i < objs.Count; i++)
{
var excelRange = (Range)ws.Cells[i, 1];
excelRange.Value2 = objs[i].val;//Value2?
excelRange = null;
}
}
catch (Exception ex)
{
string str = ex.Message;
}
finally
{
wb.Saved = true;
wb.SaveCopyAs(fileName);// save
app.Quit();// Close the process
}
}
}
class objtype
{
public string name { get; set; }
public string val { get; set; }
}
}