需求:格式為exp的文件,具有json結構,替換掉其中某些數據 解決方法:讀取excel,用npoi讀取指定內容,在exp中找到特定結構,然後替換 讀取excel文件 讀取其他格式的文件也是用此方法 public void OpenExcel() { Microsoft.Win32.OpenFile ...
需求:格式為exp的文件,具有json結構,替換掉其中某些數據
解決方法:讀取excel,用npoi讀取指定內容,在exp中找到特定結構,然後替換
讀取excel文件
讀取其他格式的文件也是用此方法
public void OpenExcel()
{
Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
if (openFileDialog.ShowDialog() == true)
{
ExcelPath = openFileDialog.FileName;
}
}
關鍵代碼
找到json的特定結構,替換數據
{
"Name": "Raw Data",
"Version": "",
"FieldName": "TakeOffPointID,CurveID,CurveData",
"FieldType": "i,s,arr",
"Data": null,
"DataList": [
"-1,A01.Green,32231.000 32695.000 31543.000 31639.000 31623.000 31367.000 31271.000 30807.000 30007.000 29895.000 29911.000 30103.000 29559.000 29607.000 29415.000 29735.000 29799.000 29495.000 29463.000 29015.000 29287.000 29639.000 30375.000 32071.000 35704.000 42474.000 51324.000 60334.000 65535.000 65535.000 65535.000 65535.000 65535.000 65535.000 65535.000 65535.000 65535.000 65535.000 65535.000 65535.000",]
}
// 使用正則表達式查找目標 JSON 結構
string pattern = $@"\{{[^{{}}]*""Name"":\s*""{sheetName}""[^{{}}]*\}}";
System.Text.RegularExpressions.Match match = Regex.Match(json, pattern, RegexOptions.Singleline);
if (match.Success)
{
// 獲取匹配的 JSON 結構
string jsonStructure = match.Value;
// 解析 JSON 數據
JObject jObject = JObject.Parse(jsonStructure);
// 查找 "DataList" 數組並替換內容
JArray dataList = (JArray)jObject["DataList"];
// 替換 "DataList" 的內容
dataList.ReplaceAll(newDataList.Select(item => new JValue(item)));
// 更新 JSON 結構
string updatedJsonStructure = jObject.ToString(Formatting.None);
// 替換原始文本中的 JSON 結構
json = Regex.Replace(json, pattern, updatedJsonStructure);
}
全部代碼
public partial class XlsxToExpViewModel : ObservableObject
{
[ObservableProperty] private string _excelPath = @"C:\Users\63214\Desktop\20220809_160644C15256.xlsx";
[ObservableProperty] private string _expPath = @"C:\ProgramData\Virtue\Experiment\20220809_160644C.exp";
[ObservableProperty] private string _newExpPath = @"C:\Users\63214\Desktop\newExp.exp";
[ObservableProperty] private double _schedule = 0;
public XlsxToExpViewModel()
{
}
#region Excel
[RelayCommand]
public void OpenExcel()
{
Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
if (openFileDialog.ShowDialog() == true)
{
ExcelPath = openFileDialog.FileName;
}
}
[RelayCommand]
public void OpenExp()
{
Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
if (openFileDialog.ShowDialog() == true)
{
ExpPath = openFileDialog.FileName;
}
}
[RelayCommand]
public void Export()
{
//配置文件目錄
string dict = null;
//IOUtil.Exists(dict);
Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog()
{
Title = "請選擇導出配置文件...", //對話框標題
Filter = "Exp Files(*.exp)|*.exp", //文件格式過濾器
FilterIndex = 1, //預設選中的過濾器
FileName = "newfile", //預設文件名
DefaultExt = "exp", //預設擴展名
InitialDirectory = dict, //指定初始的目錄
OverwritePrompt = true, //文件已存在警告
AddExtension = true, //若用戶省略擴展名將自動添加擴展名
};
if (sfd.ShowDialog() == true)
{
NewExpPath = sfd.FileName;
}
}
[RelayCommand]
public void GenerateNewExpFile()
{
if (File.Exists(NewExpPath))
{
File.Delete(NewExpPath);
Console.WriteLine("文件已刪除。");
}
// 指定要讀取的工作表名稱
List<string> listSheet = new List<string>() { "Raw Data", "Calibrated Data", "Amplification Data" };
string json = File.ReadAllText(ExpPath);
foreach (string sheetName in listSheet)
{
try
{
// 使用FileStream打開Excel文件
using (FileStream fs = new FileStream(ExcelPath, FileMode.Open, FileAccess.ReadWrite))
{
// 使用XSSFWorkbook打開.xlsx文件(如果是.xls文件,使用HSSFWorkbook)
IWorkbook workbook = new XSSFWorkbook(fs);
// 獲取指定工作表
ISheet sheet = workbook.GetSheet(sheetName);
if (sheet != null)
{
List<string> newDataList = new List<string>();
// 獲取指定sheet的內容並添加到list集合
// 遍歷列
for (int columnIndex = 1; columnIndex < sheet.GetRow(0).LastCellNum; columnIndex++)
{
string data = "-1," + sheet.GetRow(0).GetCell(columnIndex) + ",";
//string data = "-1,";
// 遍歷行
for (int row = 1; row <= sheet.LastRowNum; row++)
{
IRow currentRow = sheet.GetRow(row);
if (currentRow != null)
{
ICell cell = currentRow.GetCell(columnIndex);
if (cell != null)
{
// 獲取單元格的值(假設它是文本)
string cellValue = Convert.ToDouble(cell.ToString()).ToString("F3") + " ";
data += cellValue;
}
}
}
newDataList.Add(data);
}
// 使用正則表達式查找目標 JSON 結構
string pattern = $@"\{{[^{{}}]*""Name"":\s*""{sheetName}""[^{{}}]*\}}";
System.Text.RegularExpressions.Match match = Regex.Match(json, pattern, RegexOptions.Singleline);
if (match.Success)
{
// 獲取匹配的 JSON 結構
string jsonStructure = match.Value;
// 解析 JSON 數據
JObject jObject = JObject.Parse(jsonStructure);
// 查找 "DataList" 數組並替換內容
JArray dataList = (JArray)jObject["DataList"];
// 替換 "DataList" 的內容
dataList.ReplaceAll(newDataList.Select(item => new JValue(item)));
// 更新 JSON 結構
string updatedJsonStructure = jObject.ToString(Formatting.None);
// 替換原始文本中的 JSON 結構
json = Regex.Replace(json, pattern, updatedJsonStructure);
}
else
{
Console.WriteLine("未找到目標結構.");
}
}
else
{
Console.WriteLine("工作表 " + sheetName + " 不存在.");
}
}
}
catch (Exception ex)
{
Console.WriteLine("發生錯誤: " + ex.Message);
}
}
// 保存更新後的文本迴文件
File.WriteAllText(NewExpPath, json);
MessageBoxX.Show(Application.Current.MainWindow, "新文件已生成!", "提示", MessageBoxButton.OK, MessageBoxIcon.Success, DefaultButton.YesOK, 5);
}
#endregion
}