我正在制作一个适用于Excel文件的程序。我需要它来尝试打开现有的Excel文件,或者如果它不存在则创建一个新文件,用于读写选项。而且我必须在不使用OleDb的情况下这样做。所以问题是,当我点击按钮时,它会尝试创建一个新的Excel文件,即使我已经在目录中有该文件。有想法该怎么解决这个吗?所有用户输入必须从WinForm完成。这是我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace test2
{
public partial class Form1 : Form
{
Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRng;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FileInfo fi = new FileInfo(@"C:\Users\User\Desktop\data.xls");
if (!fi.Exists)
{
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(System.Reflection.Missing.Value));
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
oSheet.Cells[1, 1] = "First Name";
oSheet.Cells[1, 2] = "Last Name";
oSheet.Cells[1, 3] = "Full Name";
oSheet.Cells[1, 4] = "Age";
oSheet.get_Range("A1", "D1").Font.Bold = true;
oSheet.get_Range("A1", "D1").VerticalAlignment =
Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
}
else
{
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
string myPath = (@"C:\Users\User\Desktop\data.xlsx");
excelApp.Workbooks.Open(myPath);
excelApp.Visible = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
另外,如果有人能给我一个代码示例来保存和关闭Excel文件而不与用户交互,我将不胜感激。用户输入数据然后单击按钮,它将自动保存并关闭Excel文档,而不会向用户显示任何弹出窗口。
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
string myPath = (@"C:\Users\User\Desktop\data.xlsx");
excelApp.Workbooks.Open(myPath);
excelApp.Visible = false;
int rowIndex = 2; int colIndex = 2;
excelApp.Cells[rowIndex, colIndex] = textBox1.Text;
//how do I save workbook?
//how do I colose Workbook?
提前致谢。
答案 0 :(得分:1)
首先,我肯定会推荐使用Visual Studio Tools for Office( VSTO ),如果你碰巧有一个新版本的Visual Studio,比如2010.你可以在该框架内创建Excel项目,加快您的开发时间。如果您想了解更多相关信息,请点击此处:http://msdn.microsoft.com/en-US/office/hh133430.aspx
要回答有关从WinForm应用程序保存Excel工作簿的问题,您可以执行以下操作:
excelApp.ScreenUpdating = false;
excelApp.DisplayAlerts = false;
excelApp.ActiveWorkbook.Save();
excelApp.ScreenUpdating = true;
excelApp.DisplayAlerts = true;
希望有帮助,但如果还有其他任何内容,请告知我们。
答案 1 :(得分:0)
excelWorkbook.SaveAs(filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
excelWorkbook.Close();
excelApp.Quit();