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

时间:2013-04-09 10:05:04

标签: c# asp.net excel

我正在尝试在上传时清理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文件)。

任何人都可以给我一些指示吗?

3 个答案:

答案 0 :(得分:2)

好的,最后拼凑出一种有效的解决方案(足以满足我目前的用途),但远非理想:

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
    {//}
}

-EDIT-为了实现这一点,我必须在Excel中打开.xlsx文件并将其另存为.xls

答案 1 :(得分:1)

我已使用此代码更新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);
        }

答案 2 :(得分:0)

我并没有真正使用所以这(可能)不会使用代码。

C#中的Interop应该非常简单,文档通常包含特定于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
    {//}
}