效果如下:
using System.Data;
using System.IO;
using System.Windows;
using Microsoft.Win32;
using ExcelDataReader;
using System.Text;
using ClosedXML.Excel;
namespace IfoxDemo
{
public partial class SimpleWindow : Window
{
public SimpleWindow()
{
InitializeComponent();
}
private void OnSelectFileButtonClick(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog
{
Filter = "Excel Files|*.xls;*.xlsx;*.xlsm"
};
if (openFileDialog.ShowDialog() == true)
{
string filePath = openFileDialog.FileName;
System.Data.DataTable dataTable = ReadExcelFile(filePath);
//dataGrid.HeadersVisibility = DataGridHeadersVisibility.None; // Hide the header row
dataGrid.ItemsSource = dataTable.DefaultView;
}
}
private void OnSaveFileButtonClick(object sender, RoutedEventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog
{
Filter = "Excel Files|*.xlsx",
DefaultExt = "xlsx"
};
if (saveFileDialog.ShowDialog() == true)
{
string filePath = saveFileDialog.FileName;
SaveDataGridToExcel(filePath);
}
}
private System.Data.DataTable ReadExcelFile(string filePath)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
var result = reader.AsDataSet();
return result.Tables[0];
}
}
}
private void SaveDataGridToExcel(string filePath)
{
var dataTable = ((DataView)dataGrid.ItemsSource).ToTable();
// Remove the first row
using (var workbook = new XLWorkbook())
{
var worksheet = workbook.Worksheets.Add(dataTable, "Sheet1");
workbook.SaveAs(filePath);
}
}
}
}
<Window x:Class="IfoxDemo.SimpleWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="SimpleWindow" Height="500" Width="600">
<Grid>
<StackPanel>
<Button Content="选择Excel文件" Margin="10" Click="OnSelectFileButtonClick"/>
<Button Content="保存修改后的数据" Margin="10" Click="OnSaveFileButtonClick"/>
<DataGrid Name="dataGrid" AutoGenerateColumns="True" Margin="10"
HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible"
Height="300" CanUserResizeColumns="True" />
</StackPanel>
</Grid>
</Window>
using System.Collections;
using System.Collections.Generic;
using static IFoxCAD.Cad.OpFilter;
namespace IfoxDemo
{
public class 生成迷宫
{
[CommandMethod("xx")]
public void Demo()
{
using var tr = new DBTrans();
tr.Database.EraseAll();
Env.Editor.WriteMessage("开始生成迷宫1");
if (System.Windows.Application.Current == null)
{
new System.Windows.Application { ShutdownMode = ShutdownMode.OnExplicitShutdown };
}
// 显示WPF窗口
System.Windows.Application.Current.Dispatcher.Invoke(() =>
{
var window = new SimpleWindow();
window.ShowDialog();
});
}
}
}