如何保存工作簿而不显示带有Excel互操作的保存对话框? [英] How to save workbook without showing save dialog with Excel interop?

查看:72
本文介绍了如何保存工作簿而不显示带有Excel互操作的保存对话框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须创建一个将DataSet导出到Excel的控制台应用程序.问题在于它不应该弹出保存窗口,它应该自动创建Excel文件.到目前为止,我有以下代码,但是我不知道如何使其自动保存.不胜感激.

I have to create a Console application that exports a DataSet to Excel. The problem is that it shouldn't pop up the save window, it should automatically create the Excel file. So far I have the following code, but I don't know how to make it save automatically. Would appreciate any help.

public static void CreateWorkbook(DataSet ds, String path)
{
    int rowindex = 0;
    int columnindex = 0;

    Microsoft.Office.Interop.Excel.Application wapp = new Microsoft.Office.Interop.Excel.Application();
    Microsoft.Office.Interop.Excel.Worksheet wsheet;
    Microsoft.Office.Interop.Excel.Workbook wbook;

    wapp.Visible = false;

    wbook = wapp.Workbooks.Add(true);
    wsheet = (Worksheet)wbook.ActiveSheet;

    try
    {
        for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
        {
            wsheet.Cells[1, i + 1] = ds.Tables[0].Columns[i].ColumnName;

        }

        foreach (DataRow row in ds.Tables[0].Rows)
        {
            rowindex++;
            columnindex = 0;
            foreach (DataColumn col in ds.Tables[0].Columns)
            {
                columnindex++;
                wsheet.Cells[rowindex + 1, columnindex] = row[col.ColumnName];
            }
        }
    }
    catch (Exception ex)
    {
        String err = ex.Message;
    }
    wapp.UserControl = true;
}

推荐答案

WorkBook.SaveAs()的所有参数都是可选的,但如果需要,可以对大多数参数使用Type.Missing.

All of the arguments to WorkBook.SaveAs() are optional, but you can just use Type.Missing for most of them if you want to.

典型的通话如下:

wbook.SaveAs("c:\\temp\\blah", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
            false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
wbook.Close();

请注意,我没有添加文件扩展名; Excel会为您设置.

Note that I didn't include the file extension; Excel will set that for you.

查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆