Microsoft.Office.Interop.Excel 导出Excel

private const int OLDOFFICEVESION = -4143;
        private const int NEWOFFICEVESION = 56;
        /// <summary>
        /// 使用 Excel.dll  导出 Excel
        /// </summary>
        /// <param name="list">数据</param>
        /// <param name="filename">名称</param>
        /// <param name="ColumNames">标题名(数组-所有标题)</param>
        /// <param name="FileNames">标题名对应的数据库字段名称(数组-标题对应字段)</param>
        public void InteropToExcel<T>(IList<T> list, string filename, string[] ColumNames, string[] FileNames)
        {
            PropertyInfo[] propertyInfos = list.First().GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); 

            //保存excel文件的格式
            int FormatNum;
            //excel版本号
            string Version;
            Application xlApp = new Application();
            Workbooks workbooks = xlApp.Workbooks;
            //创建文件
            Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
            //创建sheet
            Worksheet worksheet = (Worksheet)workbook.Worksheets[1];
            //这里是 Excel 表格中 第一行第一列的位置是[1,1]  不是 [0,0]
            // 设置Excel 表格中 第一行的标题 字体居中
            for (int i = 0; i < ColumNames.Length; i++)
            {
                worksheet.Cells[1, i + 1] = ColumNames[i];
                ((Range)worksheet.Cells[1, i + 1]).HorizontalAlignment = XlVAlign.xlVAlignCenter;
            }
            foreach(T item in list)
            {
                if (list == null)
                {
                    return;
                }
                for (int i = 0; i < FileNames.Length; i++)
                {
                    for (int j = 0; j < propertyInfos.Length; j++)
                    {
                        PropertyInfo pi = propertyInfos[i];
                        if(pi.Name == FileNames[i])
                        {
                            worksheet.Cells[i + 2, i + 1] = pi.GetValue(item, null).ToString();
                        }
                    }   
                }
            }
            //添加内容
            
            worksheet.StandardWidth = 15d; // 设置宽度
                                           //获取你使用的excel 的版本号
            Version = xlApp.Version;
            //使用Excel 97-2003
            if (Convert.ToDouble(Version) < 12)
            {
                FormatNum = OLDOFFICEVESION;
            }
            //使用 excel 2007或更新
            else
            {
                FormatNum = NEWOFFICEVESION;
            }
            //保存,这里必须指定FormatNum文件的格式,否则无法打开创建的excel文件
            workbook.SaveAs(filename, FormatNum);
            //显示创建的excel文件
            xlApp.Visible = true;
        }

猜你喜欢

转载自www.cnblogs.com/wrq6/p/9122719.html