我的代码创建数据并将其填充到Excel文件中。问题是,当我要进行一些更改并添加更多信息时,它会告诉该文件已存在。我知道问题出在这部分,因为代码另存为新文件,并告诉您该名称的文件已经存在。有任何想法吗? 代码已更新!
try
{
Excel.Application app = new Excel.Application();
app.DisplayAlerts = false;
if (File.Exists("C:\\Users\\Adil Aliyev\\Documents\\log.xlsx")) { ObjWorkBook.Save(); MessageBox.Show("Saved"); }
else
{
ObjWorkBook.SaveAs("log.xlsx", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlExclusive, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
MessageBox.Show("created");
}
ObjWorkBook.Close();
app.Quit();
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
答案 0 :(得分:0)
我用来使其工作的完整代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
namespace Excel_Save_Over_Existing_File
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btSave_Click(object sender, EventArgs e)
{
Excel.Application oApp;
Excel.Workbook oBook;
Excel.Worksheet oSheet;
oApp.DisplayAlerts = false;
string fileTest = "C:\\Users\\Adil Aliyev\\Documents\\log.xlsx";
if (File.Exists(fileTest))
{
File.Delete(fileTest);
}
oApp = new Excel.Application();
oBook = oApp.Workbooks.Add();
oSheet = (Excel.Worksheet)oBook.Worksheets.get_Item(1);
oSheet.Cells[1, 1] = "1";
oSheet.Cells[1, 2] = "0";
oSheet.Cells[2, 1] = "0";
oSheet.Cells[2, 2] = "1";
oBook.SaveAs(fileTest);
oBook.Close();
oApp.Quit();
}
}
}
请注意,我使用您的路径是为了使您更容易理解。我在Excel文件中添加的值仅供我测试,而不是那些oSheet.Cells[1, 1] = "1";
行,您必须插入创建要保存在Excel文件中的数据的代码。
这对我来说就像是一种魅力,希望它也对您有用。祝你今天愉快! (: