最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】C#读取excel文件,并且追加内容到最后一行

C# crifan 9946浏览 0评论

【问题】

之前已经搞懂如何新建一个excel,写入header行,然后已经保存好了:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
private void createOutputFile(string excelFullFilename)
{
    bool isAutoFit = true;
    bool isHeaderBold = true;
     
    Excel.Application xlApp = new Excel.Application();
    Excel.Workbook xlWorkBook;
    Excel.Worksheet xlWorkSheet;
 
    object misValue = System.Reflection.Missing.Value;
    xlApp = new Excel.ApplicationClass();
    xlWorkBook = xlApp.Workbooks.Add(misValue);
    xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
 
    const int excelRowHeader = 1;
    const int excelColumnHeader = 1;
     
    //save header
    int curColumnIdx = 0 + excelColumnHeader;
    int rowIdx = 0 + excelRowHeader;
 
    xlWorkSheet.Cells[rowIdx, curColumnIdx++] = "Title";
    xlWorkSheet.Cells[rowIdx, curColumnIdx++] = "Description";
    const int constBullerLen = 5;
    for (int bulletIdx = 0; bulletIdx < constBullerLen; bulletIdx++)
    {
        int bulletNum = bulletIdx + 1;
        xlWorkSheet.Cells[rowIdx, curColumnIdx + bulletIdx] = "Bullet" + bulletNum.ToString();
    }
    curColumnIdx = curColumnIdx + constBullerLen;
    const int constImgNameListLen = 5;
    for (int imgIdx = 0; imgIdx < constImgNameListLen; imgIdx++)
    {
        int imgNum = imgIdx + 1;
        xlWorkSheet.Cells[rowIdx, curColumnIdx + imgIdx] = "ImageFilename" + imgNum.ToString();
    }
    curColumnIdx = curColumnIdx + constImgNameListLen;
    xlWorkSheet.Cells[rowIdx, curColumnIdx++] = "HighestPrice";
    xlWorkSheet.Cells[rowIdx, curColumnIdx++] = "OneSellerIsAmazon";
    xlWorkSheet.Cells[rowIdx, curColumnIdx++] = "ReviewNumber";
    xlWorkSheet.Cells[rowIdx, curColumnIdx++] = "IsBestSeller";
 
    //formatting
    //(1) header to bold
    if (isHeaderBold)
    {
        Range headerRow = xlWorkSheet.get_Range("1:1", System.Type.Missing);
        headerRow.Font.Bold = true;
    }
    //(2) auto adjust column width (according to content)
    if (isAutoFit)
    {
        Range allColumn = xlWorkSheet.Columns;
        allColumn.AutoFit();
    }
 
    //output
    xlWorkBook.SaveAs(excelFullFilename,
                        XlFileFormat.xlWorkbookNormal,
                        misValue,
                        misValue,
                        misValue,
                        misValue,
                        XlSaveAsAccessMode.xlExclusive,
                        XlSaveConflictResolution.xlLocalSessionChanges,
                        misValue,
                        misValue,
                        misValue,
                        misValue);
    xlWorkBook.Close(true, misValue, misValue);
    xlApp.Quit();
 
    crl.releaseObject(xlWorkSheet);
    crl.releaseObject(xlWorkBook);
    crl.releaseObject(xlApp);
}

现在需要用C#去打开已经存在的一个excel,并且找到最后一行,然后按行,继续添加内容。

【解决过程】

1.参考:

How to append existing excel file using C# ?

貌似给出办法了。

 

2.但是自己写代码期间,发现很多参数,给的不是很合适,所以又参考官网的:

Workbooks.Open Method

去自己改改。

最终如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
private void appendInfoToFile(string fullFilename, AmazonProductInfo productInfo)
{
    Excel.Application xlApp;
    Excel.Workbook xlWorkBook;
    Excel.Worksheet xlWorkSheet;
    object missingVal = System.Reflection.Missing.Value;
 
    xlApp = new Microsoft.Office.Interop.Excel.Application();
    //xlApp.Visible = true;
    //xlApp.DisplayAlerts = false;
 
    xlWorkBook = xlApp.Workbooks.Open(
        Filename : fullFilename,
        //UpdateLinks:3,
        ReadOnly : false,
        //Format : 2, //use Commas as delimiter when open text file
        //Password : missingVal,
        //WriteResPassword : missingVal,
        //IgnoreReadOnlyRecommended: false, //when save to readonly, will notice you
        Origin: Excel.XlPlatform.xlWindows, //xlMacintosh/xlWindows/xlMSDOS
        //Delimiter: ",",  // usefule when is text file
        Editable : true,
        Notify : false,
        //Converter: missingVal,
        AddToMru: true, //True to add this workbook to the list of recently used files
        Local: true,
        CorruptLoad: missingVal //xlNormalLoad/xlRepairFile/xlExtractData
        );
 
    //Get the first sheet
    xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); //also can get by sheet name
    Excel.Range range = xlWorkSheet.UsedRange;
    //int usedColCount = range.Columns.Count;
    int usedRowCount = range.Rows.Count;
 
    const int excelRowHeader = 1;
    const int excelColumnHeader = 1;
 
    //int curColumnIdx = usedColCount + excelColumnHeader;
    int curColumnIdx = 0 + excelColumnHeader; //start from column begin
    int curRrowIdx = usedRowCount + excelRowHeader; // !!! here must added buildin excelRowHeader=1, otherwise will overwrite previous (added title or whole row value)
 
    xlWorkSheet.Cells[curRrowIdx, curColumnIdx++] = productInfo.title;
    xlWorkSheet.Cells[curRrowIdx, curColumnIdx++] = productInfo.description;
 
    const int constBullerLen = 5;
    int bulletListLen = 0;
    if (productInfo.bulletArr.Length > constBullerLen)
    {
        bulletListLen = constBullerLen;
    }
    else
    {
        bulletListLen = productInfo.bulletArr.Length;
    }
    for (int bulletIdx = 0; bulletIdx < bulletListLen; bulletIdx++)
    {
        xlWorkSheet.Cells[curRrowIdx, curColumnIdx + bulletIdx] = productInfo.bulletArr[bulletIdx];
    }
    curColumnIdx = curColumnIdx + bulletListLen;
 
    const int constImgNameListLen = 5;
    int imgNameListLen = 0;
    if (productInfo.imgFullnameArr.Length > constImgNameListLen)
    {
        imgNameListLen = constImgNameListLen;
    }
    else
    {
        imgNameListLen = productInfo.imgFullnameArr.Length;
    }
    for (int imgIdx = 0; imgIdx < imgNameListLen; imgIdx++)
    {
        xlWorkSheet.Cells[curRrowIdx, curColumnIdx + imgIdx] = productInfo.imgFullnameArr[imgIdx];
    }
    curColumnIdx = curColumnIdx + imgNameListLen;
 
    xlWorkSheet.Cells[curRrowIdx, curColumnIdx++] = productInfo.highestPrice;
    xlWorkSheet.Cells[curRrowIdx, curColumnIdx++] = productInfo.isOneSellerIsAmazon;
    xlWorkSheet.Cells[curRrowIdx, curColumnIdx++] = productInfo.reviewNumber;
    xlWorkSheet.Cells[curRrowIdx, curColumnIdx++] = productInfo.isBestSeller;
 
    //xlWorkBook.SaveAs(
    //    Filename: fullFilename,
    //    ConflictResolution: XlSaveConflictResolution.xlLocalSessionChanges //The local user's changes are always accepted.
    //    //FileFormat : Excel.XlFileFormat.xlWorkbookNormal
    //);
 
    //if use above SaveAs -> will popup a window ask you overwrite it or not, even if you have set the ConflictResolution to xlLocalSessionChanges, which should not ask, should directly save
    xlWorkBook.Save();
 
    xlWorkBook.Close(SaveChanges : true);
 
    crl.releaseObject(xlWorkSheet);
    crl.releaseObject(xlWorkBook);
    crl.releaseObject(xlApp);
}

 

【总结】

别人的代码,只是供参考,不能直接拷贝,因为很多内容写的不够清楚。

想要搞清楚内部的参数的详细含义,还是要去找官网的资料,其解释的很详细和清楚。

转载请注明:在路上 » 【已解决】C#读取excel文件,并且追加内容到最后一行

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

网友最新评论 (1)

  1. 复制来有意思?
    yijiu986年前 (2018-12-02)回复
85 queries in 0.218 seconds, using 22.17MB memory