c#生成excel示例sql数据库导出excel

Jcinta ·
更新时间:2024-11-10
· 933 次阅读

代码如下:
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 &l t; 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; }
    }
}

您可能感兴趣的文章:C#窗体读取EXCEL并存入SQL数据库的方法C#实现Excel导入sqlite的方法C#将Sql数据保存到Excel文件中的方法C#怎样才能将XML文件导入SQL ServerC#基于COM方式读取Excel表格的方法C#使用Aspose.Cells控件读取ExcelC#读取Excel的三种方式以及比较分析C#实现把txt文本数据快速读取到excel中ASP.NET(C#)读取Excel的文件内容C#实现Excel表数据导入Sql Server数据库中的方法



C# SQL sql数据库

需要 登录 后方可回复, 如果你还没有账号请 注册新账号