本文主要是介绍c# NPOI 运用反射实现通用性方法导出excel 简单明了,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
private void Export_Click(object sender, RoutedEventArgs e)
{var list = tiDulegendService.GetStepSuspendList();var type = typeof(TiDuStepSuspend);PropertyInfo[] properties = type.GetProperties();Console.WriteLine("属性:");// Export_Click// 创建一个工作簿对象IWorkbook workbook = new XSSFWorkbook();// 创建一个工作表对象ISheet sheet = workbook.CreateSheet("Sheet1");// 创建标题行IRow headerRow = sheet.CreateRow(0);for (int i = 0; i < properties.Length; i++){headerRow.CreateCell(i).SetCellValue(properties[i].Name);}//Type type = myObject.GetType();//PropertyInfo property = type.GetProperty("MyProperty");//object value = property.GetValue(myObject);//Console.WriteLine(value); //输出:Hello World// 填充数据行for (int i = 0; i < list.Count; i++){IRow dataRow = sheet.CreateRow(i + 1);Type types = list[i].GetType();PropertyInfo[] propertiess = types.GetProperties();for (int j = 0; j < propertiess.Length; j++){PropertyInfo property = type.GetProperty(propertiess[j].Name);var value = property.GetValue(list[i]);dataRow.CreateCell(j).SetCellValue(value.ToString());}}// 调整列宽sheet.AutoSizeColumn(0);sheet.AutoSizeColumn(1);// 读取已存在的 Excel 文件using (FileStream fileStream = new FileStream("test.xls", FileMode.Create)){workbook.Write(fileStream);}
}
这篇关于c# NPOI 运用反射实现通用性方法导出excel 简单明了的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!