将List中部分字段转换为DataTable中
由于原来方法导出数据量比较大 的时候,出现卡顿现象:搜索简单改造:(下面方法借助NPIO)
/// <summary> /// 将List中原文和译文转换为Datatable /// </summary> /// <typeparam name="MemoryFields">术语</typeparam> /// <param name="list">术语列宁表</param> /// <returns>只包含原文和译文的DataTable</returns> public System.Data.DataTable list2Datatable<MemoryFields>(List<MemoryFields> list) { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(MemoryFields)); System.Data.DataTable dt = new System.Data.DataTable(); //for (int i = 0; i < properties.Count; i++) //{ PropertyDescriptor propertyOrig = properties["Orig"];//Orig为字段 dt.Columns.Add("原文", propertyOrig.PropertyType); PropertyDescriptor propertyTran = properties["Tran"]; //Tran为字段 dt.Columns.Add("译文", propertyTran.PropertyType); //} object[] values = new object[2]; foreach (MemoryFields item in list) { //for (int i = 0; i < values.Length; i++) //{ values[0] = properties["Orig"].GetValue(item); values[1] = properties["Tran"].GetValue(item); //} dt.Rows.Add(values); } return dt; }
private string filename = ""; private IWorkbook workbook = null; private FileStream fs = null; private bool disposed; /// <summary> /// 到处到Excel /// </summary> /// <param name="FileName">导出文件名</param> /// <param name="data">table</param> /// <param name="sheetName">sheetName</param> /// <param name="isColumnWritten"></param> /// <returns></returns> public int DataTableToExcel(string FileName, System.Data.DataTable data, string sheetName, bool isColumnWritten) { filename = FileName; int i = 0; int j = 0; int count = 0; ISheet sheet = null; fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite); if (filename.IndexOf(".xlsx") > 0) // 2007版本 workbook = new XSSFWorkbook(); else if (filename.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(); try { if (workbook != null) { sheet = workbook.CreateSheet(sheetName); } else { return -1; } if (isColumnWritten == true) //写入DataTable的列名 { IRow row = sheet.CreateRow(0); for (j = 0; j < data.Columns.Count; ++j) { row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName); } count = 1; } else { count = 0; } for (i = 0; i < data.Rows.Count; ++i) { IRow row = sheet.CreateRow(count); for (j = 0; j < data.Columns.Count; ++j) { row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString()); } ++count; } workbook.Write(fs); //写入到excel return count; } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); return -1; } }