一、读取Excel文件,需要在电脑上安装Excel,然后新建一个excel文件命名为demo.xlsx,在表格第一行第一列填入Hello World!。然后在程序中引入COM,本例中读取一个Excel文件后直接关闭同时清理了Excel进程。
MainWindow.xaml文件代码(按键盘→键可以看到右侧被挡住的代码)
using System;
using System.Windows;
using Microsoft.Office.Interop.Excel;
namespace WpfApp10
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : System.Windows.Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
object miss = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Workbook workbook = app.Application.Workbooks.Open(@"C:\Users\qc\Desktop\demo.xlsx", miss, false);
Worksheet worksheet = workbook.Worksheets.Item["Sheet1"];
label1.Content = worksheet.Cells[1, 1].Value2 as string;
app.Quit();
}
private void Grid_Click(object sender, RoutedEventArgs e)
{
GC.Collect();
}
}
}
MainWindow.xaml文件代码(按键盘→键可以看到右侧被挡住的代码)
<Window x:Class="WpfApp10.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp10"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid ButtonBase.Click="Grid_Click">
<Label x:Name="label1" Content="Label" HorizontalAlignment="Left" Margin="215,151,0,0" VerticalAlignment="Top" Width="247" Height="52"/>
<Button Click="Button_Click" Content="获取Excel文件内容" HorizontalAlignment="Left" Margin="215,263,0,0" VerticalAlignment="Top" Width="247" Height="63"/>
</Grid>
</Window>
代码效果如下:
代码效果
网友评论