C# 将List数据写入Excel

将List中的额数据写入Excel

由于是Excel文件,所以要用到Office相关的dll,故请添加相应dll的引用,然后在程序中添加如下命名空间:

using Microsoft.Office.Interop.Excel;

 

自定义类:


    public class Student

    {

        private string id;

        public string Id { get { return id; } set { id = value; } }

 

        private string name;

        public string Name { get { return name; } set { name = value; } }

 

        private string age;

        public string Age { get { return age; } set { age = value; } }

    }
添加模拟数据:


        private List<Student> GetStudentData()

        {

            List<Student> studentList = new List<Student>();

 

            Student s1 = new Student();

            s1.Id = "1";

            s1.Name = "haha";

            s1.Age = "10";

 

            Student s2 = new Student();

            s2.Id = "2";

            s2.Name = "xixi";

            s2.Age = "20";

 

            Student s3 = new Student();

            s3.Id = "3";

            s3.Name = "lolo";

            s3.Age = "30";

 

            studentList.Add(s1);

            studentList.Add(s2);

            studentList.Add(s3);

 

            return studentList;

        }
用反射获取类型的所有属性(以便后续生成所有Column的标题):


        private PropertyInfo[] GetPropertyInfoArray()

        {

            PropertyInfo[] props = null;

            try

            {

                Type type = typeof(EricSunApp.Student);

                object obj = Activator.CreateInstance(type);

                props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

            }

            catch (Exception ex)

            { }

            return props;

        }
遍历List,将数据保存成Excel文件:


        private void SaveDataToExcelFile(List<Student> studentList, string filePath)

        {

            object misValue = System.Reflection.Missing.Value;

            Application xlApp = new Application();

            Workbook xlWorkBook = xlApp.Workbooks.Add(misValue);

            Worksheet xlWorkSheet = (Worksheet)xlWorkBook.Worksheets.get_Item(1);

 

            PropertyInfo[] props = GetPropertyInfoArray();

            for (int i = 0; i < props.Length; i++)

            {

                xlWorkSheet.Cells[1, i + 1] = props[i].Name; //write the column name

            }

            for (int i = 0; i < studentList.Count; i++)

            {

                xlWorkSheet.Cells[i + 2, 1] = studentList[i].Id;

                xlWorkSheet.Cells[i + 2, 2] = studentList[i].Name;

                xlWorkSheet.Cells[i + 2, 3] = studentList[i].Age;

            }

            try

            {

                xlWorkBook.SaveAs(filePath, XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

                xlWorkBook.Close(true, misValue, misValue);

                xlApp.Quit();

            }

            catch (Exception ex)

            { }

 

      }

结束。


//下面这段代码是SaveAs()的格式

expression.SaveAs(FileName, FileFormat, Password, WriteResPassword, ReadOnlyRecommended, CreateBackup, AccessMode, ConflictResolution, AddToMru, TextCodepage, TextVisualLayout, Local);
 

 原文链接:https://blog.csdn.net/qq_30507287/article/details/53856267

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中,可以使用NPOI库来实现对Excel文件的写入操作。具体步骤如下: 1. 引入NPOI库,可以通过NuGet包管理器来安装。 2. 创建一个Workbook对象,表示一个Excel文件。 3. 创建一个Sheet对象,表示一个工作表。 4. 创建行和单元格对象,设置单元格的值。 5. 将行对象添加到工作表中。 6. 将工作表添加到Workbook对象中。 7. 将Workbook对象写入Excel文件中。 下面是一个示例代码,演示如何将数据写入Excel文件中: ``` using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using System.Collections.Generic; using System.IO; public class Supply { public string Value1 { get; set; } public string Value2 { get; set; } public string Value3 { get; set; } } public void WriteToExcel(List<Supply> data, string filePath) { // 创建一个Workbook对象,表示一个Excel文件 IWorkbook workbook = new HSSFWorkbook(); // 创建一个Sheet对象,表示一个工作表 ISheet sheet = workbook.CreateSheet("Sheet1"); // 创建行和单元格对象,设置单元格的值 int rowIndex = 0; foreach (Supply supply in data) { IRow row = sheet.CreateRow(rowIndex++); row.CreateCell(0).SetCellValue(supply.Value1); row.CreateCell(1).SetCellValue(supply.Value2); row.CreateCell(2).SetCellValue(supply.Value3); } // 将Workbook对象写入Excel文件中 using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { workbook.Write(fs); } } ``` 在上面的代码中,我们首先创建了一个Workbook对象,然后创建了一个Sheet对象,表示一个工作表。接着,我们遍历数据列表,创建行和单元格对象,并设置单元格的值。最后,将Workbook对象写入Excel文件中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值