public partial class Form1 : Form
{
FileInfo Excelfile;
ExcelPackage package;
ExcelWorksheet sheet1 = null;
public Form1()
{
InitializeComponent();
//屏幕上控件:
//TextBox控件,命名为txtExcelPath,用于记录选中的Excel文件地址
//button控件,命名为btnExcel,用于文件开窗选择
//comboBox控件,命名为comboBoxExcel,用于记录Excel各工作表名称
}
private void btnExcel_Click(object sender, EventArgs e) //表示不可以多选
{
OpenFileDialog OFDExcel = new OpenFileDialog();
OFDExcel.InitialDirectory = @"D:\My_Study\C#\项目库\Excel操作";
OFDExcel.Filter = "(*.xlsx)|*.xlsx|(*.xls)|*.xls";
OFDExcel.Multiselect = false; //表示不可以多选
if (OFDExcel.ShowDialog() == DialogResult.OK)
{
txtExcelPath.Text = System.IO.Path.GetFullPath(OFDExcel.FileName);
Excelfile = new FileInfo(txtExcelPath.Text);
package = new ExcelPackage(Excelfile);
ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.Commercial;
int sheetCount = package.Workbook.Worksheets.Count;
for (int k = 0; k < sheetCount; k++)
{
comboBoxExcel.Items.Add(package.Workbook.Worksheets[k].Name);
}
comboBoxExcel.Text = comboBoxExcel.Items[0].ToString();
}
}
}
读取Excel工作表并将名称填入下拉框控件中
于 2023-10-02 17:11:21 首次发布