Excel转Json
导入EPPlus插件
引用命名空间:OfficeOpenXml、Newtonsoft.Json
示例代码:
public static void ConvertExcelToJson(string excelFilePath, string jsonFilePath)
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
FileInfo excelFile = new FileInfo(excelFilePath);
if (!excelFile.Exists)
{
Console.WriteLine("Excel file does not exist.");
return;
}
using (var package = new ExcelPackage(excelFile))
{
var worksheet = package.Workbook.Worksheets[0];
var rows = worksheet.Cells;
var rowCount = worksheet.Dimension.End.Row;
var columnCount = worksheet.Dimension.End.Column;
List<Dictionary<string, string>> data = new List<Dictionary<string, string>>();
// Assuming the first row contains column headers
for (int row = 2; row <= rowCount; row++)
{
if (string.IsNullOrEmpty(worksheet.GetValue<string>(row, 1)))
continue;
Dictionary<string, string> rowData = new Dictionary<string, string>();
for (int col = 1; col <= columnCount; col++)
{
if (string.IsNullOrEmpty(worksheet.GetValue<string>(1, col)))
continue;
string header = worksheet.Cells[1, col].Text;
string cellValue = worksheet.Cells[row, col].Text;
rowData[header] = cellValue;
}
data.Add(rowData);
}
string jsonData = JsonConvert.SerializeObject(data, Formatting.Indented);
jsonFilePath = $"{Path.GetDirectoryName(excelFilePath)}\\{Path.GetFileNameWithoutExtension(excelFilePath)}_{worksheet.Name}.json";
File.WriteAllText(jsonFilePath, jsonData);
Console.WriteLine("Excel data has been converted to JSON and saved to " + jsonFilePath);
}
}
Excel转Xml
导入EPPlus插件
引用命名空间:OfficeOpenXml、System.Xml
示例代码:
public static void ConvertExcelToXml(string excelFilePath, string xmlFilePath)
{
using (var package = new ExcelPackage(new FileInfo(excelFilePath)))
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
var worksheet = package.Workbook.Worksheets[0];
var rowCount = worksheet.Dimension.End.Row;
var columnCount = worksheet.Dimension.End.Column;
var xmlDoc = new XmlDocument();
var rootElement = xmlDoc.CreateElement("Data");
xmlDoc.AppendChild(rootElement);
for (int row = 2; row <= rowCount; row++)
{
if (string.IsNullOrEmpty(worksheet.GetValue<string>(row, 1)))
continue;
var rowElement = xmlDoc.CreateElement("Row");
rootElement.AppendChild(rowElement);
for (int col = 1; col <= columnCount; col++)
{
if (string.IsNullOrEmpty(worksheet.GetValue<string>(1, col)))
continue;
var cellKey = worksheet.Cells[1, col].Text;
var cellValue = worksheet.Cells[row, col].Text;
var cellElement = xmlDoc.CreateElement(cellKey);
cellElement.InnerText = cellValue;
rowElement.AppendChild(cellElement);
}
}
xmlFilePath = $"{Path.GetDirectoryName(excelFilePath)}\\{Path.GetFileNameWithoutExtension(excelFilePath)}_{worksheet.Name}.xml";
xmlDoc.Save(xmlFilePath);
}
}