C# 替换或更新Excel文件中的条目

C# 替换或更新Excel文件中的条目,c#,asp.net,excel,C#,Asp.net,Excel,我试图在上传时清除Excel(.xlsx)文件中的一些数据(本例中为电话号码)。我有以下代码来打开该文件: protected void Button1_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) try { string filePath = ("confirm//") + FileUpload1.FileName; FileUp

我试图在上传时清除Excel(.xlsx)文件中的一些数据(本例中为电话号码)。我有以下代码来打开该文件:

protected void Button1_Click(object sender, EventArgs e)
{
    if (FileUpload1.HasFile)
        try
        {
            string filePath = ("confirm//") + FileUpload1.FileName;
            FileUpload1.SaveAs(Server.MapPath(filePath));

            Microsoft.Office.Interop.Excel.Application xl = 
                new Microsoft.Office.Interop.Excel.Application();

            Workbook wb = 
                xl.Application.Workbooks.Open(Server.MapPath(filePath));

            wb.Activate();
            string csvPath = (filePath.Replace(".xlsx", ".csv"));

            wb.SaveAs(Server.MapPath(csvPath), 
                Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV);

            wb.Close();             

            // call method to parse csv
            ReadRec(csvPath);
        }
        catch (Exception ex)
        {//}
    else
    {//}
}
然后像这样在数字的开头添加一个零(如果还没有):

private void ReadRec(string csvName)
{
    StreamReader Sr = new StreamReader(Server.MapPath(csvName));
    string s;

    while (!Sr.EndOfStream)
    {
        s = Sr.ReadLine();

        string company = s.Split(',')[0];
        string phone = s.Split(',')[1];
        string NAME = s.Split(',')[2];

        if (!phone.StartsWith("0"))
        {
            phone = "0" + phone;
        }
    }
    Sr.Close();
}
这似乎很有效,但我还没有弄清楚如何将更新后的数字重新插入电子表格(或使用更新后的数据创建一个新的Excel文件)

有人能给我一些建议吗?

我没有真正使用过,或者这(可能)不会是有效的代码

C#中的互操作应该非常简单,文档中通常有特定于C#的示例,因此如果失败,请查看MSDN

protected void Button1_Click(object sender, EventArgs e)
{
    if (FileUpload1.HasFile)
        try
        {
            string filePath = ("confirm//") + FileUpload1.FileName;
            FileUpload1.SaveAs(Server.MapPath(filePath));

            Microsoft.Office.Interop.Excel.Application xl = 
                new Microsoft.Office.Interop.Excel.Application();

            Workbook wb = 
                xl.Application.Workbooks.Open(Server.MapPath(filePath));

            wb.Activate();

            Worksheet ws = wb.Worksheets(1); // use the first sheet 1-based index i think

            for (long row = 2; i <= ws.UsedRange.Rows.Count; i++) {
                // assume row 1 is a title so start at row 2
                // ws.Cells(row, 1) // company
                // ws.Cells(row, 2) // phone
                // ws.Cells(row, 3) // name
                if (!ws.Cells(row,2).Value2.StartsWith("0") {
                    ws.Cells(row,2).Value2 = "0" + ws.Cells(row,2).Value2
                }
            }

            //string csvPath = (filePath.Replace(".xlsx", ".csv"));

            //wb.SaveAs(Server.MapPath(csvPath), 
            //    Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV);
            wb.Save(); // as were directly modifying the file, no need to save elsewhere

            wb.Close();             

            // call method to parse csv
            //ReadRec(csvPath);
        }
        catch (Exception ex)
        {//}
    else
    {//}
}
受保护的无效按钮1\u单击(对象发送者,事件参数e)
{
if(FileUpload1.HasFile)
尝试
{
字符串filePath=(“确认/”)+FileUpload1.FileName;
FileUpload1.SaveAs(Server.MapPath(filePath));
Microsoft.Office.Interop.Excel.Application xl=
新的Microsoft.Office.Interop.Excel.Application();
工作簿wb=
xl.Application.Workbooks.Open(Server.MapPath(filePath));
wb.Activate();
工作表ws=wb.Worksheets(1);//我想使用第一个基于工作表1的索引

对于(long row=2;iOK),我最终拼凑出了一个解决方案,这种解决方案很有效(对于我目前的目的来说已经足够了),但还远远不够理想:

protected void Button1_Click(object sender, EventArgs e)
{       
    if (FileUpload1.HasFile)
        try
        {
            var excelApp = new Application();
            excelApp.Workbooks.Open("C:\\myFile.xls", Type.Missing, Type.Missing,
                                                   Type.Missing, Type.Missing,
                                                   Type.Missing, Type.Missing,
                                                   Type.Missing, Type.Missing,
                                                   Type.Missing, Type.Missing,
                                                   Type.Missing, Type.Missing,
                                                   Type.Missing, Type.Missing);
            var ws = excelApp.Worksheets;
            var worksheet = (Worksheet)ws.get_Item("Sheet1");
            Range range = worksheet.UsedRange;
            object[,] values = (object[,])range.Value2;

            for (int row = 1; row <= values.GetUpperBound(0); row++)
            {
                string phone = Convert.ToString(values[row, 2]);
                if (!phone.StartsWith("0"))
                {
                    phone = "0" + phone;
                }
                range.Cells.set_Item(row, 2, phone);
            }
            excelApp.Save("C:\\Leads.xls");
            excelApp.Quit();
       }
        catch (Exception ex)
        {//}
    else
    {//}
}
受保护的无效按钮1\u单击(对象发送者,事件参数e)
{       
if(FileUpload1.HasFile)
尝试
{
var excelApp=新应用程序();
excelApp.Workbooks.Open(“C:\\myFile.xls”,类型.缺失,类型.缺失,
类型。缺失,类型。缺失,
类型。缺失,类型。缺失,
类型。缺失,类型。缺失,
类型。缺失,类型。缺失,
类型。缺失,类型。缺失,
类型。缺失,类型。缺失);
var ws=excelApp.工作表;
var工作表=(工作表)ws.get_项(“Sheet1”);
范围=工作表.UsedRange;
对象[,]值=(对象[,])范围。值2;

对于(int row=1;row,我使用此代码更新EXCEL工作表中的数据

 try
        {
            cmd.CommandText = "UPDATE [Sheet1$] SET ID=@value,Name=@value2,Age=@value3 where ID=@value4";
            cn.Open();
            cmd.Parameters.AddWithValue("@value1", txtid.Text);
            cmd.Parameters.AddWithValue("@value2", txtname.Text);
            cmd.Parameters.AddWithValue("@value3", txtage.Text);
            cmd.Parameters.AddWithValue("@value4", txtupdate.Text);
            cmd.ExecuteNonQuery();
            MessageBox.Show("Record Updated Successfully");
            cn.Close();
        }
        catch (Exception e3)
        {
            MessageBox.Show("Error" + e3);
        }

这个文件有多大?在同一个文件上读写确实有问题。你能在内存中加载所有内容吗?你能写入excel吗?它相当大,大约10000行长。@Kyle:你是说把数据写入一个新文件?那很好,但我也不知道如何做。如果你想输出为xls(x)然后在excel文件上执行操作,而不是首先将其转换为CSV。谢谢。检索单元格内容时遇到困难。我尝试了
行。单元格[2]。Value.ToString();
但它抛出的
对象不包含值定义
错误。@LucaZiegler您没有错。我也提到过它可能不起作用。什么是cmd?什么是cn?只有部分解决方案没有多大帮助!