定义数据结构
public class Info
{
public string Info1 { get; set; } = string.Empty;
public string Info2 { get; set; } = string.Empty;
public string Info3 { get; set; } = string.Empty;
public string Info4 { get; set; } = string.Empty;
}
获取数据结构
public void GetInfo(string FilePath)
{
Excel.Application excelApp = null;
Excel.Workbook workbook = null;
Excel.Worksheet worksheet = null;
try
{
string FileName = string.Empty;
FileName = Path.GetFileNameWithoutExtension(FilePath);
excelApp = new Excel.Application();
workbook = excelApp.Workbooks.Open(FilePath);
worksheet = workbook.Worksheets["Sheet1"]; // 第一个工作表
int rowCount = worksheet.UsedRange.Rows.Count;
for (int row = 2; row <= rowCount; row++) // 假设第一行为标题
{
Info tmp = new Info();
tmp.Info1 = worksheet.Cells[row, 1].Text;
tmp.Info2 = worksheet.Cells[row, 2].Text;
tmp.Info3 = worksheet.Cells[row, 3].Text;
tmp.Info4 = worksheet.Cells[row, 4].Text;
}
}
finally
{
// 确保释放 COM 对象
if (worksheet != null) Marshal.ReleaseComObject(worksheet);
if (workbook != null)
{
workbook.Close();
Marshal.ReleaseComObject(workbook);
}
if (excelApp != null)
{
excelApp.Quit();
Marshal.ReleaseComObject(excelApp);
}
}
}