好的,我们来分析和修改你的 ArcMap Add-in 代码。
主要问题有两个:
- 自定义读取: 需要让用户指定工作表、行范围和列。
.xlsx 错误: Microsoft.ACE.OLEDB.12.0 未注册。
解决方案
-
.xlsx 错误:
- 根本原因: 这是因为运行 ArcMap 的计算机上没有安装 "Microsoft Access Database Engine" (ACE) OLE DB 提供程序,或者安装的版本与 ArcMap 的位数(32位 vs 64位)不匹配。ArcMap 32位应用程序需要 32位的 ACE 驱动。
- 推荐方法: 放弃 OLE DB,改用一个可以直接读写 Excel 文件的 .NET 库,这样可以完全避免对 ACE 驱动的依赖。EPPlus 是一个非常流行且强大的库,支持
.xlsx (以及 .xls 的部分功能,但主要针对新格式)。
- 替代方法 (不推荐): 安装匹配的 ACE 驱动(32位),但这增加了部署复杂性。或者在代码中根据文件扩展名尝试不同的提供程序 (
Microsoft.Jet.OLEDB.4.0 for .xls, Microsoft.ACE.OLEDB.12.0 for .xlsx),但这并不能解决驱动未安装的问题。
-
自定义读取:
- 用户界面: 需要一种方式让用户输入工作表名、起始行、结束行、列字母。最简单的方法是使用几个
MessageBox.Show 配合输入,或者创建一个简单的 WinForms 窗体。我们将使用一个简化的输入框实现。
- 代码逻辑: 修改读取函数,使其接受这些参数,并使用 EPPlus 库来执行读取。
修改后的代码
首先,你需要将 EPPlus 添加到你的 ArcMap Add-in 项目中。
- 在 Visual Studio 中,右键点击你的项目 -> "管理 NuGet 程序包..."
- 搜索 "EPPlus" 并安装它。
- 重要: EPPlus 5.0 及更高版本需要你设置
LicenseContext。在代码的某个地方(例如类的静态构造函数或每次使用前)添加 ExcelPackage.LicenseContext = LicenseContext.NonCommercial; (如果你是商业使用,请购买许可证并使用 LicenseContext.Commercial;)。
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
// using System.Data.OleDb; // OLE DB不再需要,可以注释掉或删除
using OfficeOpenXml; // 引入 EPPlus 命名空间
using System.Linq; // 用于 LINQ 操作,例如 string.Join
namespace ArcMapAddin2
{
public class ArcGISAddin1 : ESRI.ArcGIS.Desktop.AddIns.Button
{
public ArcGISAddin1()
{
// 设置 EPPlus 的许可上下文。
// 对于 EPPlus 5.0 及以上版本,这是必需的。
// 根据你的使用情况选择 NonCommercial 或 Commercial。
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
}
protected override void OnClick()
{
// 1. 打开文件对话框选择 Excel 文件
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Excel Files (*.xls, *.xlsx)|*.xls;*.xlsx";
openFileDialog.Title = "请选择 Excel 文件"; // 设置对话框标题
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string excelFilePath = openFileDialog.FileName;
// 2. 获取用户输入的参数 (工作表名, 起始行, 结束行, 列字母)
string sheetName = ShowInputDialog("请输入要读取的工作表名称:", "工作表名称", "Sheet1");
if (sheetName == null) return; // 用户取消
string startRowStr = ShowInputDialog("请输入起始行号:", "起始行", "1");
if (startRowStr == null) return; // 用户取消
if (!int.TryParse(startRowStr, out int startRow) || startRow <= 0)
{
MessageBox.Show("无效的起始行号。请输入一个正整数。", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
string endRowStr = ShowInputDialog($"请输入结束行号 (>= {startRow}):", "结束行", startRow.ToString());
if (endRowStr == null) return; // 用户取消
if (!int.TryParse(endRowStr, out int endRow) || endRow < startRow)
{
MessageBox.Show($"无效的结束行号。请输入一个大于或等于 {startRow} 的数字。", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
string columnLetter = ShowInputDialog("请输入要读取的列字母 (例如 A, B, C, AA):", "列字母", "A");
if (columnLetter == null) return; // 用户取消
// 可以添加更复杂的列字母验证逻辑 (例如,确保是有效的字母组合)
// 3. 读取 Excel 数据
try
{
List<object> values = ReadExcelColumnRange(excelFilePath, sheetName, startRow, endRow, columnLetter);
// 4. 显示读取到的数据
if (values != null && values.Count > 0)
{
// 将读取到的值合并成一个字符串显示
string resultString = $"从 '{Path.GetFileName(excelFilePath)}' 的 '{sheetName}' 工作表读取到数据 (行 {startRow}-{endRow}, 列 {columnLetter}):\n\n";
resultString += string.Join("\n", values.Select(v => v?.ToString() ?? "[空单元格]")); // 处理空值
MessageBox.Show(resultString, "读取成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show($"在 '{sheetName}' 工作表的 {columnLetter}{startRow}:{columnLetter}{endRow} 范围内未找到数据。", "未找到数据", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
catch (FileNotFoundException)
{
MessageBox.Show($"错误:文件 '{excelFilePath}' 未找到。", "文件错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex)
{
// 捕获 EPPlus 可能抛出的其他异常 (如工作表不存在、列/行无效等)
MessageBox.Show($"读取 Excel 文件时发生错误:\n{ex.Message}\n\n请确认工作表名称 '{sheetName}' 和指定的行/列范围是否正确。", "读取错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// 使用 EPPlus 读取指定Excel文件、工作表、行范围和列的值。
/// </summary>
/// <param name="filePath">Excel 文件路径</param>
/// <param name="sheetName">工作表名称</param>
/// <param name="startRow">起始行号 (1-based)</param>
/// <param name="endRow">结束行号 (1-based)</param>
/// <param name="columnLetter">列字母 (例如 "A", "B", "AA")</param>
/// <returns>包含指定列数据的对象列表</returns>
private List<object> ReadExcelColumnRange(string filePath, string sheetName, int startRow, int endRow, string columnLetter)
{
List<object> columnValues = new List<object>();
int columnNumber = ColumnLetterToIndex(columnLetter); // 将列字母转换为数字索引
FileInfo fileInfo = new FileInfo(filePath);
if (!fileInfo.Exists)
{
throw new FileNotFoundException("指定的 Excel 文件不存在。", filePath);
}
// EPPlus 的许可设置(确保在加载文件前完成)
// ExcelPackage.LicenseContext = LicenseContext.NonCommercial; // 已经在构造函数或OnCreate中设置
using (var package = new ExcelPackage(fileInfo))
{
// 获取工作表
var worksheet = package.Workbook.Worksheets[sheetName];
if (worksheet == null)
{
// 尝试不区分大小写查找
worksheet = package.Workbook.Worksheets.FirstOrDefault(ws => ws.Name.Equals(sheetName, StringComparison.OrdinalIgnoreCase));
if (worksheet == null)
{
throw new Exception($"在 Excel 文件中未找到名为 '{sheetName}' 的工作表。");
}
}
// 验证行和列的有效性
if (columnNumber <= 0 || columnNumber > worksheet.Dimension.End.Column)
{
throw new Exception($"指定的列 '{columnLetter}' 超出了工作表 '{sheetName}' 的范围 (最大列: {worksheet.Dimension.End.Column})。");
}
if (startRow <= 0 || endRow > worksheet.Dimension.End.Row || startRow > endRow)
{
throw new Exception($"指定的行范围 ({startRow}-{endRow}) 超出了工作表 '{sheetName}' 的范围 (最大行: {worksheet.Dimension.End.Row}) 或格式无效。");
}
// 遍历指定范围的行,读取指定列的值
for (int i = startRow; i <= endRow; i++)
{
// worksheet.Cells[row, column] - 行和列都是从1开始的索引
var cellValue = worksheet.Cells[i, columnNumber].Value;
columnValues.Add(cellValue);
}
}
return columnValues;
}
/// <summary>
/// 将 Excel 列字母 (例如 "A", "B", "AA") 转换为从1开始的列索引。
/// </summary>
private int ColumnLetterToIndex(string letter)
{
if (string.IsNullOrEmpty(letter)) return 0;
int columnIndex = 0;
string upperLetter = letter.ToUpper(); // 转换为大写以统一处理
for (int i = 0; i < upperLetter.Length; i++)
{
// 检查字符是否为有效字母
if (upperLetter[i] < 'A' || upperLetter[i] > 'Z')
{
throw new ArgumentException($"无效的列字母 '{letter}'。");
}
// 计算索引: A=1, B=2, ..., Z=26, AA=27, AB=28, ...
columnIndex = columnIndex * 26 + (upperLetter[i] - 'A' + 1);
}
return columnIndex;
}
/// <summary>
/// 显示一个简单的输入对话框 (模拟 VB的 InputBox)。
/// </summary>
/// <param name="prompt">提示信息</param>
/// <param name="title">对话框标题</param>
/// <param name="defaultValue">默认值</param>
/// <returns>用户输入的字符串,如果用户取消则返回 null</returns>
private string ShowInputDialog(string prompt, string title, string defaultValue = "")
{
// 在你的ArcMap Add-in项目中,你需要添加一个WinForms Form。
// 右键点击项目 -> 添加 -> Windows 窗体... (命名为 InputForm.cs)
// 在 InputForm.cs 的设计器中,添加一个 Label, 一个 TextBox, 一个 OK 按钮, 一个 Cancel 按钮。
// 设置 Label 的 Text 为 prompt,TextBox 的 Text 为 defaultValue。
// 设置 OK 按钮的 DialogResult 为 OK,Cancel 按钮的 DialogResult 为 Cancel。
// 在 OK 按钮的 Click 事件处理中,将 TextBox.Text 赋值给窗体的 public InputValue 属性。
// 下面是 InputForm.cs 的示例代码(假设你已创建此文件并添加了控件):
/*
// ---- InputForm.cs ----
using System;
using System.Windows.Forms;
public partial class InputForm : Form
{
public string InputValue { get; private set; } = null;
public InputForm(string prompt, string title, string defaultValue = "")
{
InitializeComponent(); // 如果使用设计器,则调用此方法
// --- 如果不使用设计器,手动初始化控件 ---
// this.Text = title;
// this.Size = new System.Drawing.Size(350, 150);
// this.StartPosition = FormStartPosition.CenterScreen;
// Label promptLabel = new Label() { Left = 10, Top = 10, Text = prompt, AutoSize = true };
// TextBox inputTextBox = new TextBox() { Left = 10, Top = 35, Width = 306, Text = defaultValue };
// Button okButton = new Button() { Left = 100, Top = 80, Text = "OK", DialogResult = DialogResult.OK };
// Button cancelButton = new Button() { Left = 180, Top = 80, Text = "Cancel", DialogResult = DialogResult.Cancel };
// this.Controls.Add(promptLabel);
// this.Controls.Add(inputTextBox);
// this.Controls.Add(okButton);
// this.Controls.Add(cancelButton);
// this.AcceptButton = okButton;
// this.CancelButton = cancelButton;
// okButton.Click += (sender, e) => { this.InputValue = inputTextBox.Text; };
// this.CenterToScreen();
// -----------------------------------------
}
// 如果使用了设计器,InitializeComponent() 会在 InputForm.Designer.cs 文件中自动生成
// 你需要确保设计器正确设置了控件和事件
}
*/
// 假设你已经创建了名为 InputForm 的 Windows 窗体
using (var form = new InputForm(prompt, title, defaultValue))
{
if (form.ShowDialog() == DialogResult.OK)
{
return form.InputValue; // 返回用户输入的值
}
}
return null; // 用户点击了取消或关闭了对话框
}
protected override void OnUpdate()
{
// 在这里可以添加启用/禁用按钮的逻辑,例如检查当前是否有活动的地图文档
// this.Enabled = ArcMap.Document != null;
}
}
// --- 在你的项目中添加一个名为 InputForm.cs 的文件 ---
// 右键点击项目 -> 添加 -> Windows 窗体... -> 命名为 InputForm.cs
// --- InputForm.cs 的内容 ---
/*
using System;
using System.Windows.Forms;
using System.Drawing; // 需要引入 System.Drawing
// Make the class public and ensure it's accessible
public partial class InputForm : Form
{
public string InputValue { get; private set; } = null;
// Constructor - assuming you have added controls via the designer
public InputForm(string prompt, string title, string defaultValue = "")
{
InitializeComponent(); // This method is generated by the designer
// Set properties from parameters
this.Text = title;
this.promptLabel.Text = prompt; // Assuming you named the label 'promptLabel'
this.inputTextBox.Text = defaultValue; // Assuming you named the textbox 'inputTextBox'
// Ensure the OK button sets the InputValue
this.okButton.Click += (sender, e) => {
this.InputValue = this.inputTextBox.Text;
// The DialogResult property handles closing the form
};
// Ensure the form centers correctly (might need adjustment based on control sizes)
this.CenterToScreen();
}
// IMPORTANT: If you use the form designer (double-click the file in Solution Explorer),
// it will create InputForm.Designer.cs. Ensure that file is also included.
// The designer code will contain the actual creation and setup of the controls.
// You would typically have:
// private System.Windows.Forms.Label promptLabel;
// private System.Windows.Forms.TextBox inputTextBox;
// private System.Windows.Forms.Button okButton;
// private System.Windows.Forms.Button cancelButton;
// in the InputForm.Designer.cs file, initialized in InitializeComponent().
}
*/
// --- 你还需要在 InputForm.Designer.cs 文件中看到类似下面的内容 ---
/*
partial class InputForm
{
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null)) { components.Dispose(); }
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.promptLabel = new System.Windows.Forms.Label();
this.inputTextBox = new System.Windows.Forms.TextBox();
this.okButton = new System.Windows.Forms.Button();
this.cancelButton = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// promptLabel
//
this.promptLabel.AutoSize = true;
this.promptLabel.Location = new System.Drawing.Point(12, 15);
this.promptLabel.MaximumSize = new System.Drawing.Size(300, 0); // Allow word wrap
this.promptLabel.Name = "promptLabel";
this.promptLabel.Size = new System.Drawing.Size(70, 15); // Default size, will be adjusted
this.promptLabel.TabIndex = 0;
this.promptLabel.Text = "Prompt:";
//
// inputTextBox
//
this.inputTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)));
this.inputTextBox.Location = new System.Drawing.Point(15, 40);
this.inputTextBox.Name = "inputTextBox";
this.inputTextBox.Size = new System.Drawing.Size(300, 23);
this.inputTextBox.TabIndex = 1;
//
// okButton
//
this.okButton.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right;
this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.okButton.Location = new System.Drawing.Point(100, 80);
this.okButton.Name = "okButton";
this.okButton.Size = new System.Drawing.Size(75, 25);
this.okButton.TabIndex = 2;
this.okButton.Text = "OK";
this.okButton.UseVisualStyleBackColor = true;
//
// cancelButton
//
this.cancelButton.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right;
this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancelButton.Location = new System.Drawing.Point(180, 80);
this.cancelButton.Name = "cancelButton";
this.cancelButton.Size = new System.Drawing.Size(75, 25);
this.cancelButton.TabIndex = 3;
this.cancelButton.Text = "Cancel";
this.cancelButton.UseVisualStyleBackColor = true;
//
// InputForm
//
this.ClientSize = new System.Drawing.Size(275, 120); // Adjust size as needed
this.Controls.Add(this.cancelButton);
this.Controls.Add(this.okButton);
this.Controls.Add(this.inputTextBox);
this.Controls.Add(this.promptLabel);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "InputForm";
this.Text = "InputForm"; // Title set in constructor
this.AcceptButton = this.okButton; // Set OK button to trigger on Enter
this.CancelButton = this.cancelButton; // Set Cancel button to trigger on Escape
this.MaximizeBox = false;
this.MinimizeBox = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; // Center on screen
this.ResumeLayout(false);
this.PerformLayout(); // Ensure layout is correct after adding controls
}
// Declare the controls here if not using the designer, or ensure they are declared in InputForm.cs
private System.Windows.Forms.Label promptLabel;
private System.Windows.Forms.TextBox inputTextBox;
private System.Windows.Forms.Button okButton;
private System.Windows.Forms.Button cancelButton;
}
*/
}