我正在制作一个适用于 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?
提前致谢。