接上篇

1,界面Xaml代码如下,界面布局如图1所示。

    <Grid>
        <StackPanel>
            <Label Name="name1" Width="70" Height="30" HorizontalAlignment="Left" Margin="10" VerticalAlignment="Top" Background="Gold"></Label>
            <Label Name="age1" Width="70" Height="30" HorizontalAlignment="Left" Margin="10" VerticalAlignment="Top" Background="Gold"></Label>
            <Label Name="height1" Width="70" Height="30" HorizontalAlignment="Left" Margin="10" VerticalAlignment="Top" Background="Gold"></Label>
        </StackPanel>
        
        <StackPanel>
            <TextBox Name="name2" Width="100" Height="30" HorizontalAlignment="Left" Margin="100,10,10,10" VerticalAlignment="Top" Background="AntiqueWhite"></TextBox>
            <TextBox Name="age2" Width="100" Height="30" HorizontalAlignment="Left" Margin="100,10,10,10" VerticalAlignment="Top" Background="AntiqueWhite"></TextBox>
            <TextBox Name="height2" Width="100" Height="30" HorizontalAlignment="Left" Margin="100,10,10,10" VerticalAlignment="Top" Background="AntiqueWhite"></TextBox>
        </StackPanel>

        <StackPanel Orientation="Horizontal">
            <Button Name="Read" Margin="10,100,10,10" Height="30" Width="80" HorizontalAlignment="Left" Click="Read_Click">读取数据</Button>
            <Button Name="cancel" Margin="10,100,10,10" Height="30" Width="80" HorizontalAlignment="Left" Click="cancel_Click">取消</Button>
        </StackPanel>
        
    </Grid>

C#读写Excel(2)_WPF

图1

后台代码写在“读取数据”按钮下,程序运行结果如图2所示。

        private void Read_Click(object sender, RoutedEventArgs e)
        {
            // 创建Excel对象

            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

            //打开文件路径
            String filePath = "C:/000/hx.xls";

            Workbook workbook = excel.Workbooks.Open(filePath);

            // 获取第一个工作表

            Worksheet worksheet = workbook.Sheets[1];

            // 获取单元格值

            Range range = worksheet.UsedRange;

            name1.Content= (range.Cells[1, 1] as Range).Value.ToString();

            age1.Content= (range.Cells[1, 2] as Range).Value.ToString();

            height1.Content = (range.Cells[1, 3] as Range).Value.ToString();

            name2.Text=(range.Cells[2, 1] as Range).Value.ToString();

            age2.Text = (range.Cells[2, 2] as Range).Value.ToString();

            height2.Text= (range.Cells[2, 3] as Range).Value.ToString();

            // 关闭Excel对象

            workbook.Close();

            excel.Quit();
        }

C#读写Excel(2)_WPF_02

图2