0
点赞
收藏
分享

微信扫一扫

C#读写Excel(1)

何以至千里 2023-11-27 阅读 63

1,下载VS插件

首先从VS的Nuget下载 Microsoft.Office.Interop.Excel插件,写程序时将其引用using Microsoft.Office.Interop.Excel;

2,excel写入

界面Xaml代码:创建了3个TextBox接收值。

    <Grid>
        <StackPanel>
            <Label Width="100" Height="30" HorizontalAlignment="Left" Margin="10">姓名</Label>
            <Label Width="100" Height="30" HorizontalAlignment="Left" Margin="10">年龄</Label>
            <Label Width="100" Height="30" HorizontalAlignment="Left" Margin="10">身高</Label>
        </StackPanel>

        <StackPanel>
            <TextBox Name="name" Margin="100,10,10,10" Width="100" Height="30" HorizontalAlignment="Left"></TextBox>
            <TextBox Name="age" Margin="100,10,10,10" Width="100" Height="30" HorizontalAlignment="Left"></TextBox>
            <TextBox Name="height" Margin="100,10,10,10" Width="100" Height="30" HorizontalAlignment="Left"></TextBox>
        </StackPanel>

        <StackPanel Orientation="Horizontal">
            <Button Name="accept" Margin="10,100,10,10" Width="100" Height="30" Click="accept_Click">确定</Button>
            <Button Name="cancel" Margin="10,100,10,10" Width="100" Height="30">取消</Button>
        </StackPanel>
    </Grid>

C#读写Excel(1)_C#

图1 界面布局

后台代码,写在“确定”按钮中。运行结果如图2图3所示。此程序也可操作WPS的 .xlsx,将路径中的文件后缀改成 .xlsx即可。

        private void accept_Click(object sender, RoutedEventArgs e)
        {
            // 创建Excel对象
            Microsoft.Office.Interop.Excel.Application excel =new Microsoft.Office.Interop.Excel.Application();

            //创建文件路径
            string filepath = "C:/000/hx.xls";

            Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add();

            // 获取第一个工作表

            Microsoft.Office.Interop.Excel.Worksheet worksheet = workbook.Sheets[1];

            worksheet.Cells[1, 1] = "姓名";

            worksheet.Cells[1, 2] = "年龄";

            worksheet.Cells[1, 3] = "身高";

            worksheet.Cells[2, 1] = name.Text;

            worksheet.Cells[2, 2] = age.Text;

            worksheet.Cells[2, 3] = height.Text;

            // 保存Excel文件

            workbook.SaveAs(filepath);

            // 关闭Excel对象

            workbook.Close();

            excel.Quit();

            this.Close();
        }

C#读写Excel(1)_读写_02C#读写Excel(1)_WPF_03

图2输入参数                                                               图3 Excel结果

3,遇到的问题:

(a)此句代码若不写Microsoft.Office.Interop.Excel会出现图4的错误。

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

C#读写Excel(1)_Excel_04

图4 错误一

(b)同理,此句代码Window前若不写System.Windows,也会出现图5所示错误。

public partial class MainWindow : System.Windows.Window

C#读写Excel(1)_读写_05

图5 错误二

举报

相关推荐

0 条评论