Создание инструмента ExcelToJson в качестве надстройки Excel с использованием C# и VSTO.C#

Место общения программистов C#
Ответить
Anonymous
 Создание инструмента ExcelToJson в качестве надстройки Excel с использованием C# и VSTO.

Сообщение Anonymous »

Среда разработки: Visual Studio Professional 2022 (17.10.3)
Как уже упоминалось, я планирую создать надстройку Excel для преобразования Excel в JSON.
Однако в настоящее время мне не удается успешно экспортировать файл JSON в указанное место (я уже установил точки останова для проверки выполнения).
Я хотел бы попросить совета по этой проблеме и возможным решениям.
Любой предложения будут очень признательны. Спасибо!

Ниже находится файл ThisAddIn.cs.

Код: Выделить всё

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Tools.Excel;
using DocumentFormat.OpenXml.Spreadsheet;
using ClosedXML.Excel;
using Newtonsoft.Json;

namespace Excel2Json
{
public partial class ThisAddIn
{
private bool isExportEnabled = false; // Variable to save the state of the checkbox
private string exportFolderPath = @"C:(LocalPathHere)"; // Folder path for export destination

// Set the state of the checkbox
public void SetExportEnabled(bool isEnabled)
{
isExportEnabled = isEnabled; // Set the checkbox state
}

// Set the folder path for export destination
public void SetExportFolderPath(string folderPath)
{
exportFolderPath = folderPath;
}

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
// Load the state of the checkbox from the configuration file
string configFilePath = Path.Combine(exportFolderPath, "config.txt");
if (File.Exists(configFilePath))
{
string configValue = File.ReadAllText(configFilePath);
bool.TryParse(configValue, out isExportEnabled); // Restore previous state
}

// Add WorkbookBeforeClose and WorkbookBeforeSave events
this.Application.WorkbookBeforeClose += new Excel.AppEvents_WorkbookBeforeCloseEventHandler(ExportJsonOnClose);
this.Application.WorkbookBeforeSave += new Excel.AppEvents_WorkbookBeforeSaveEventHandler(ExportJsonOnSave);
}

// Correct signature for WorkbookBeforeClose
private void ExportJsonOnClose(Excel.Workbook Wb, ref bool Cancel)
{
Console.WriteLine("Workbook is closing."); // Log to confirm event trigger
if (isExportEnabled && !string.IsNullOrEmpty(exportFolderPath))
{
ExportJson(Wb);
}
}

private void ExportJsonOnSave(Excel.Workbook Wb, bool SaveAsUI, ref bool Cancel)
{
Console.WriteLine("Workbook is saving."); // Log to confirm event trigger
if (isExportEnabled && !string.IsNullOrEmpty(exportFolderPath))
{
ExportJson(Wb);
}
}

// Export to JSON
public void ExportJson(Excel.Workbook Wb)
{
try
{
// Create the export folder if it doesn't exist
if (!Directory.Exists(exportFolderPath))
{
Directory.CreateDirectory(exportFolderPath);
}

// Full path of the Excel file
string filePath = Wb.FullName;
string fileName = Path.GetFileNameWithoutExtension(filePath); // File name (without extension)
string jsonFilePath = Path.Combine(exportFolderPath, fileName + ".json"); // Path to save the .json file in the specified folder

Console.WriteLine("Exporting JSON for file: " + filePath);
Console.WriteLine("Saving JSON to: " + jsonFilePath);

using (var xlwb = new XLWorkbook(filePath))
{
var worksheet = xlwb.Worksheet("Sample1");
if (worksheet == null)
{
Console.WriteLine("The specified worksheet name 'Sample1' does not exist.");
return;
}

List excelData = new List();

foreach (var row in worksheet.RangeUsed().RowsUsed())
{
Dictionary  rowData = new Dictionary();
foreach (var cell in row.CellsUsed())
{
rowData[$"Column{cell.Address.ColumnNumber}"] = cell.GetValue();
}
excelData.Add(rowData);
}

// Convert to JSON & save to the specified folder
string json = JsonConvert.SerializeObject(excelData, Formatting.Indented);
File.WriteAllText(jsonFilePath, json);
Console.WriteLine("JSON was successfully exported and saved: " + jsonFilePath);
}
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}

private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
// Save the state of the checkbox to a file
string configFilePath = Path.Combine(exportFolderPath, "config.txt");
File.WriteAllText(configFilePath, isExportEnabled.ToString());
}

#region VSTO generated code

/// 
/// Method required for designer support.
/// Please do not change this in the code editor.
/// 
private void InternalStartup()
{

}

#endregion
}
}

Ниже находится файл Ribbon1.cs.

Код: Выделить всё

using Microsoft.Office.Tools.Ribbon;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Xml;
using System.Threading.Tasks;
using System.Drawing.Text;
using ClosedXML.Excel;
using Newtonsoft.Json;
using Microsoft.Office.Interop.Excel;
using JsonFormatting = Newtonsoft.Json.Formatting;  // Avoid ambiguity between versions
using Excel = Microsoft.Office.Interop.Excel;

namespace Excel2Json
{
public partial class Ribbon1
{
private bool isExportEnable = false;

private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
{

}

private void checkBox1_Click(object sender, RibbonControlEventArgs e)
{
bool isChecked = ((RibbonCheckBox)sender).Checked;
Globals.ThisAddIn.SetExportEnabled(isChecked);

if (isChecked)
{
// Get the currently open workbook and export
Excel.Workbook Wb = Globals.ThisAddIn.Application.ActiveWorkbook;
Globals.ThisAddIn.ExportJson(Wb);
}
}

// Export Test Button
private void button1_Click(object sender, RibbonControlEventArgs e)
{
Excel.Workbook Wb = Globals.ThisAddIn.Application.ActiveWorkbook;
Globals.ThisAddIn.ExportJson(Wb);
}
}
}

Извините, я все еще новичок и в настоящее время изучаю и исследую различные вещи.
Если в моем объяснении есть что-то неясное , пожалуйста, не стесняйтесь спрашивать.
Наконец, еще раз спасибо за помощь.

Подробнее здесь: https://stackoverflow.com/questions/791 ... p-and-vsto
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»