How to save workbook without showing save dialog with Excel interop?(如何在不显示 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.
Workbook.SaveAs 方法 (Microsoft.Office.Tools.Excel) |Microsoft Docs 描述了每个参数.
这篇关于如何在不显示 Excel 互操作的保存对话框的情况下保存工作簿?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在不显示 Excel 互操作的保存对话框的情况下保存工作簿?
基础教程推荐
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
