我正在编写用于对excel中的特定列进行排序的C#WPF简易程序,我在将变量excel.worksheet从Button_Click传递到另一个Button_Click时遇到了问题。 代码如下:
using Microsoft.Win32;
using System.IO;
using System;
using System.Windows;
using Excel = Microsoft.Office.Interop.Excel;
namespace Sorting
{
public partial class MainWindow : Window
{
int column, CounterRow;
string filepath;
Excel.Worksheet x = new Excel.Worksheet();
public MainWindow()
{
InitializeComponent();
}
private void Choose_Files_Button_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = false;
ofd.Filter = "All files (*.*)|*.*";
ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (ofd.ShowDialog() == true)
{
ListBox_Files.Items.Clear();
filepath = ofd.FileName;
ListBox_Files.Items.Add(Path.GetFileName(filepath));
}
if (ListBox_Files.Items.Count != 0) ListBox_Files.IsEnabled = Otworz.IsEnabled = true;
}
private void Button_Click_0(object sender, RoutedEventArgs e)
{
Excel.Application excel = new Excel.Application();
excel.Visible = true;
excel.DisplayAlerts = false;
Excel.Workbook sheet = excel.Workbooks.Open(filepath);
Excel.Worksheet x = excel.ActiveSheet as Excel.Worksheet;
MessageBox.Show("select column");
Sort(x,1);
MessageBox.Show("end");
excel.Quit();
}
void Button_Click(object sender, RoutedEventArgs e)
{
Excel.Application excel = new Excel.Application();
excel.Visible = true;
excel.DisplayAlerts = false;
Excel.Workbook sheet = excel.Workbooks.Open(filepath);
Excel.Worksheet x = excel.ActiveSheet as Excel.Worksheet;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Sort(x, 1);
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
Sort(x, 2);
}
private void Sort(Excel.Worksheet excel, int info)
{
Excel.Range rng = excel.Application.ActiveCell;
column = rng.Column;
Excel.Range userRange = excel.UsedRange;
CounterRow = userRange.Rows.Count;
Excel.Range range = excel.Range[excel.Cells[7, 1], excel.Cells[CounterRow - 1, 8]];
if (info == 1) range.Sort(range.Columns[column], Excel.XlSortOrder.xlAscending);
else if (info == 2) range.Sort(range.Columns[column], Excel.XlSortOrder.xlDescending);
}
}
}
任何人都可以解释一下,为什么Click_Button_0正常工作,当我通过Click_Button打开文件然后我将通过Click_Button_1排序列并单击Button_2不起作用? Visual Studio说:" System.InvalidCastException"