/// <summary> /// 保存数据到文件 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sourceData"></param> /// <param name="fileName"></param> /// <param name="sheetName"></param> public static void saveDataToFile <T>(List <T> sourceData) { Dictionary <string, string> fileinfo = getFileInfo <T>(); string fileName = fileinfo["ExcelName"]; string sheetName = fileinfo["SheetName"]; ExcelEdit excel = new ExcelEdit(); string str = System.Windows.Forms.Application.StartupPath; Worksheet ws = null; if (!Directory.Exists(str)) { Directory.CreateDirectory(str); } if (!File.Exists(str + @"\" + fileName)) { excel.mFilename = str + @"\" + fileName; excel.Create(); excel.AddSheet(sheetName); } else { excel.Open(str + @"\" + fileName); } if (excel.GetSheet(sheetName) == null) { ws = excel.AddSheet(sheetName); } else { ws = excel.GetSheet(sheetName); } int y = 2; foreach (T item in sourceData) { int x = 1; foreach (PropertyInfo obj in item.GetType().GetProperties()) { object value = null; if (y == 2) { value = obj.Name.ToString(); excel.SetCellValue(ws, 1, x, value); } value = item.GetType().GetProperty(obj.Name.ToString()).GetValue(item); Range titleRange = ws.Range[ws.Cells[y, x], ws.Cells[y, x]]; //选中标题 titleRange.HorizontalAlignment = XlHAlign.xlHAlignCenter; //水平居中 if (titleRange.Value != null && value != null && value.Equals(titleRange.Value)) { x++; continue; } else { excel.SetCellValue(ws, y, x, value); x++; } } y++; } excel.wb.RefreshAll(); if (File.Exists(str + @"\" + fileName)) { excel.Save(); } else { excel.SaveAs(str + @"\" + fileName); } excel.Close(); }