c#生成excel示例sql数据库导出excel
程序员文章站
2024-02-24 23:15:22
复制代码 代码如下:using system;using system.collections.generic;using system.linq;using system...
复制代码 代码如下:
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>
/// 直接导出数据到excel
/// </summary>
/// <param name="connectionstring">连接字符串</param>
/// <param name="sql">查询语句</param>
/// <param name="filename">文件名</param>
/// <param name="sheetname">表名</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);//保存
app.quit();//关闭进程
}
}
}
class objtype
{
public string name { get; set; }
public string val { get; set; }
}
}