Loading
0

C# Excel表格追加数据方法

技术小学生微信公众号
腾讯云服务器大促销。
华为服务器
C# Excel表格追加数据方法
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 Excel = Microsoft.Office.Interop.Excel;
using crl = System.Runtime.InteropServices.Marshal; //ReleaseComObject(Object O)

namespace 脚本编辑器_Excel追加数据
{
    public partial class Form1 : Form
    {
        
        public Form1()
        {
            
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var obj = new { Name = "lily", Age = 12 };
            appendInfoToFile(Application.StartupPath + @"\" + "vjshi销售统计表.xlsx");
        }

        //何新建一个excel,写入header行,然后已经保存好了
        public 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)
            {

                Excel.Range headerRow = xlWorkSheet.get_Range("1:1", System.Type.Missing);
                headerRow.Font.Bold = true;
            }
            //(2) auto adjust column width (according to content)
            if (isAutoFit)
            {
                Excel.Range allColumn = xlWorkSheet.Columns;
                allColumn.AutoFit();
            }

            //output
            xlWorkBook.SaveAs(excelFullFilename,
                                Excel.XlFileFormat.xlWorkbookNormal,
                                misValue,
                                misValue,
                                misValue,
                                misValue,
                                Excel.XlSaveAsAccessMode.xlExclusive,
                                Excel.XlSaveConflictResolution.xlLocalSessionChanges,
                                misValue,
                                misValue,
                                misValue,
                                misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            crl.ReleaseComObject(xlWorkSheet);
            crl.ReleaseComObject(xlWorkBook);
            crl.ReleaseComObject(xlApp);
        }

        //打开已经存在的一个excel,并且找到最后一行,然后按行,继续添加内容。
        public void appendInfoToFile(string fullFilename)//AmazonProductInfo productInfo1
        {
            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;

            //http://msdn.microsoft.com/zh-cn/library/microsoft.office.interop.excel.workbooks.open%28v=office.11%29.aspx
            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)

            curRrowIdx = curRrowIdx + 1;
            xlWorkSheet.Cells[curRrowIdx, curColumnIdx] = "222";//productInfo.title;
            xlWorkSheet.Cells[curRrowIdx, ++curColumnIdx] = "333";
            xlWorkSheet.Cells[curRrowIdx, ++curColumnIdx] = "444";
            //xlWorkSheet.Cells[curRrowIdx, curColumnIdx++] = "333";//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;
            */

            ////http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=ZH-CN&k=k%28MICROSOFT.OFFICE.INTEROP.EXCEL._WORKBOOK.SAVEAS%29;k%28SAVEAS%29;k%28TargetFrameworkMoniker-%22.NETFRAMEWORK%2cVERSION%3dV3.5%22%29;k%28DevLang-CSHARP%29&rd=true
            //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();

            //http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=ZH-CN&k=k%28MICROSOFT.OFFICE.INTEROP.EXCEL._WORKBOOK.CLOSE%29;k%28CLOSE%29;k%28TargetFrameworkMoniker-%22.NETFRAMEWORK%2cVERSION%3dV3.5%22%29;k%28DevLang-CSHARP%29&rd=true
            xlWorkBook.Close(SaveChanges: true);
            crl.ReleaseComObject(xlWorkSheet);
            crl.ReleaseComObject(xlWorkBook);
            crl.ReleaseComObject(xlApp); //releaseObject
        }
    }
}
 

 

技术小学生微信公众号
华为服务器
腾讯云服务器大促销。

声明:站长码字很辛苦啊,转载时请保留本声明及附带文章链接:https://blog.tag.gg/showinfo-23-36062-0.html
亲爱的:若该文章解决了您的问题,可否收藏+评论+分享呢?
上一篇:c#重新选择文件路径实现方法
下一篇:C#截取特定长度的字符串