我有一種情況,我需要在 .net 核心控制臺應用程式中將 excel 檔案(.xlsx)下載并保存為 .CSV 格式。
由于 Microsoft.Interop 包與 .Net core 3.1 不兼容,我還可以使用什么其他方法將 Excel 檔案另存為 .CSV?
欣賞建議。
uj5u.com熱心網友回復:
這是關于 SO 的多個現有答案的組合。
首先是從這里 使用 ClosedXML 將 xlsx 轉換為 DataTable
using ClosedXML.Excel;
...
public static DataTable GetDataFromExcel(string path, dynamic worksheet)
{
//Save the uploaded Excel file.
DataTable dt = new DataTable();
//Open the Excel file using ClosedXML.
using (XLWorkbook workBook = new XLWorkbook(path))
{
//Read the first Sheet from Excel file.
IXLWorksheet workSheet = workBook.Worksheet(worksheet);
//Create a new DataTable.
//Loop through the Worksheet rows.
bool firstRow = true;
foreach (IXLRow row in workSheet.Rows())
{
//Use the first row to add columns to DataTable.
if (firstRow)
{
foreach (IXLCell cell in row.Cells())
{
if (!string.IsNullOrEmpty(cell.Value.ToString()))
{
dt.Columns.Add(cell.Value.ToString());
}
else
{
break;
}
}
firstRow = false;
}
else
{
int i = 0;
DataRow toInsert = dt.NewRow();
foreach (IXLCell cell in row.Cells(1, dt.Columns.Count))
{
try
{
toInsert[i] = cell.Value.ToString();
}
catch (Exception ex)
{
//Handle this, or don't.
}
i ;
}
dt.Rows.Add(toInsert);
}
}
return dt;
}
如果您需要進行任何資料轉換,請在資料位于 DataTable 中時進行。
然后使用 CSVHelper 匯出為 CSV(所以我發現有一個解決方案沒有使用文化資訊,它是在幾次更新前作為要求添加到圖書館的):
using CSVHelper;
using System.Globilization;
....
public static void SaveCSV(DataTable records)
{
string newFile = @"C:\somePath.csv";
using (StreamWriter writer = new StreamWriter(newFile))
{
using (CsvWriter csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
//add headers
foreach (DataColumn dc in records.Columns)
{
csv.WriteField(dc.ColumnName);
}
csv.NextRecord();
foreach(DataRow dr in records.Rows)
{
for (int i = 0; i< records.Columns.Count; i )
{
csv.WriteField(dr[i]);
}
csv.NextRecord();
}
}
}
}
uj5u.com熱心網友回復:
如果它只是一個文字資料沒有影像那么你可以從excel復制資料并將其保存在另一個檔案中
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/364127.html
