一、DataTable轉List Json
DataTable是.NET中一個非常常用的數據類型。然而,當我們需要將DataTable轉化成其他數據類型的時候,就需要考慮DataTable轉化成List Json。下面我們就從以下幾個方面來詳細講解如何完成轉化過程。
1. 使用Json.net進行DataTable轉換
using Newtonsoft.Json;
using System.Data;
using System.Web.Mvc;
public JsonResult GetJsonData()
{
DataTable dt = GetDataTable(); //獲取DataTable數據
string json = JsonConvert.SerializeObject(dt); //DataTable轉換成Json字符串
return Json(json, JsonRequestBehavior.AllowGet); // "AllowGet" 這個參數允許 Get 方式的HTTP請求.
}
從上面的代碼中可以看出,我們通過Json.net這個類庫中的SerializeObject()函數,很容易地將DataTable轉化成了Json格式的字符串。需要注意的是,一定要在Controller層的函數中將返回類型設置成JsonResult類型,否則會引發異常。
2. 使用JavaScriptSerializer進行DataTable轉換
using System.Web.Script.Serialization;
using System.Data;
using System.Web.Mvc;
public JsonResult GetJsonData()
{
DataTable dt = GetDataTable(); //獲取DataTable數據
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(dt); //DataTable轉換成Json字符串
return Json(json, JsonRequestBehavior.AllowGet); // "AllowGet" 這個參數允許 Get 方式的HTTP請求.
}
我們也可以使用.NET自帶的JavaScriptSerializer進行DataTable轉換,它與Json.net類庫差不多,只是Transform DataTable to List Json過程多了一步,需要先實例化一個JavaScriptSerializer類。
3. 優化DataTable轉Json的性能
為了提高DataTable轉換成List Json的性能,我們可以使用異步的方式進行數據轉換。下面是代碼的實現:
public async Task<JsonResult> GetJsonData()
{
DataTable dt = GetDataTable(); //獲取DataTable數據
string json = string.Empty;
await Task.Factory.StartNew(() =>
{
json = JsonConvert.SerializeObject(dt); // DataTable轉換成Json字符串
});
return Json(json, JsonRequestBehavior.AllowGet); // "AllowGet" 這個參數允許 Get 方式的HTTP請求.
}
通過在Controller層的函數中使用Task.Factory.StartNew()方法,我們就可以將數據轉換和返回的Http響應分別掛起,從而達到提高程序性能的目的。
二、List轉DataTable
除了將DataTable轉成Json格式的字符串,還有一種常用的操作就是將List轉成DataTable。那麼,如何實現List轉DataTable呢?下面我們就從以下幾個方面詳細介紹。
1. 將List元素插入到DataTable的行中
public static DataTable ToDataTable<T>(List<T> iList)
{
DataTable dataTable = new DataTable();
PropertyDescriptorCollection propertyDescriptorCollection = TypeDescriptor.GetProperties(typeof(T));
for (int i = 0; i < propertyDescriptorCollection.Count; i++)
{
PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
Type type = propertyDescriptor.PropertyType;
if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable)))
{
type = Nullable.GetUnderlyingType(type);
}
dataTable.Columns.Add(propertyDescriptor.Name, type);
}
object[] values = new object[propertyDescriptorCollection.Count];
foreach (T iListItem in iList)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = propertyDescriptorCollection[i].GetValue(iListItem);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
通過定義ToDataTable()函數,我們可以將List轉成DataTable,並且在其中逐一遍歷List中的元素,將其插入到DataTable的每一行中,從而得到我們需要的結果。
2. 將List元素的屬性作為DataTable的列
public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable)))
{
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType));
}
else
{
table.Columns.Add(prop.Name, prop.PropertyType);
}
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
通過重載ToDataTable()函數,我們就可以將List中元素的屬性名作為DataTable的列名。這種方法在將List轉成DataTable時非常有用。
三、DataTable轉成List
DataTable直接轉為List是我們常用到的方式之一。下面我們就從以下幾個方面詳細介紹如何實現DataTable轉List操作。
1. 遍歷每一行數據轉成List元素
public static List<T> ToList<T>(this DataTable table) where T : class, new()
{
List<T> list = new List<T>();
foreach (DataRow row in table.Rows)
{
T item = new T();
foreach (DataColumn column in table.Columns)
{
PropertyInfo property = item.GetType().GetProperty(column.ColumnName);
if (property != null && row[column] != DBNull.Value)
{
property.SetValue(item, row[column], null);
}
}
list.Add(item);
}
return list;
}
將DataTable逐行遍歷,將每一行數據轉化成List元素,這是最為直接的方法。同時,在List中需要指定泛型參數類型T。
2. 使用Linq進行數據的篩選和過濾
public static List<T> ToList<T>(this DataTable table) where T : new()
{
List<T> result = new List<T>();
foreach (var row in table.AsEnumerable())
{
T item = new T();
foreach (var prop in item.GetType().GetProperties())
{
try
{
PropertyInfo propertyInfo = item.GetType().GetProperty(prop.Name);
object propertyValue = row[prop.Name];
if (propertyValue == null)
{
propertyValue = DBNull.Value;
}
propertyInfo.SetValue(item, propertyValue, null);
}
catch (Exception ex)
{
continue;
}
}
result.Add(item);
}
return result;
}
我們還可以使用Linq進行篩選和過濾操作,將DataTable轉換成指定泛型T的List。這種方式操作更為靈活,並可以直接通過Lambda表達式對數據進行操作。
四、DataTable轉Sheet
DataTable轉Sheet通常用於Excel表格的導出操作。下面我們就從以下幾個方面詳細介紹如何將DataTable轉成Sheet。
1. 使用NPOI庫轉換成Sheet
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.IO;
public ActionResult ExportExcel()
{
DataTable dt = GetDataTable(); //獲取DataTable數據
HSSFWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet("sheet1");
IRow headerRow = sheet.CreateRow(0);
for (int i = 0; i < dt.Columns.Count; i++)
headerRow.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
for (int i = 0; i < dt.Rows.Count; i++)
{
IRow row = sheet.CreateRow(i + 1);
for (int j = 0; j < dt.Columns.Count; j++)
row.CreateCell(j).SetCellValue(dt.Rows[i][j].ToString());
}
MemoryStream ms = new MemoryStream();
workbook.Write(ms);
Response.BinaryWrite(ms.ToArray());
Response.End();
return View();
}
這裡使用NPOI庫來將DataTable轉成Sheet,主要用到了HSSFWorkbook和ISheet兩個類。NPOI庫是.NET中操作Excel的最好選擇之一。
2. 使用EPPlus庫轉換成Sheet
using OfficeOpenXml;
using System.Web.Mvc;
using System.IO;
public void ExportExcel()
{
List<MyObj> myList = new List<MyObj>();
DataTable dt = myList.ToDataTable();
byte[] fileContents;
using (var package = new ExcelPackage())
{
// Add a new worksheet to the empty workbook
ExcelWorksheet worksheet = null;
worksheet = package.Workbook.Worksheets.Add("sheet1");
worksheet.Cells[1, 1].LoadFromDataTable(dt, true);
fileContents = package.GetAsByteArray();
}
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", "MyExcel.xlsx"));
Response.OutputStream.Write(fileContents, 0, fileContents.Length);
Response.OutputStream.Flush();
Response.OutputStream.Close();
Response.End();
}
使用EPPlus庫將DataTable轉成Sheet非常方便。EPPlus基於Open XML標準,支持新的Excel格式,並且速度快,使用方便。
五、Dataframe轉List
Dataframe是pandas庫中的常用數據類型,通常需要將其轉成List,以方便後續操作。以下是如何將Dataframe轉成List的幾種方法。
1. 使用values屬性轉換成List
import pandas as pd
import numpy as np
df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns=['a', 'b', 'c'])
list1 = df.values.tolist()
print(list1)
使用pandas庫中的values屬性,可以將Dataframe轉成List。Cpandas庫的values屬性是將值以數組形式返回,然後變成List。
2. 使用to_dict()方法將Dataframe轉成List
import pandas as pd
import numpy as np
df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns=['a', 'b', 'c'])
dict1 = df.to_dict('records')
print(dict1)
利用pandas庫中的to_dict()方法,可以將Dataframe轉成字典形式,然後再以字典形式返回List。
3. 合併列名和數據,並將Dataframe轉為List
import pandas as pd
import numpy as np
df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns=['a', 'b', 'c'])
result = []
for col in df.columns:
values = df[col].values
col_values = [{col: value} for value in values]
for i in range(len(col_values)):
if len(result) <= i:
result.append({})
result[i].update(col_values[i])
list1 = []
for item in result:
row = []
for col in df.columns:
row.append(item[col])
list1.append(row)
print(list1)
通過合併列名和數據兩個屬性,然後將Dataframe轉化成List。這種方法較為麻煩,但是可以準確地實現Goal。
六、DataTable轉String
將DataTable轉成String,是我們在後端計算和前端展示時常用的操作。下面我們就從如下幾個方面詳細講解如何將DataTable轉成String。
1. 拼接字符串輸出
private static string DataTable2String(DataTable dt)
{
string result = string.Empty;
for (int i = 0; i < dt.Rows.Count; i++)
{
result += dt.Rows[i]["ColumnName原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/249076.html