새 워크북에 Excel 워크시트 복사 및 저장

2160 단어
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 Excel = Microsoft.Office.Interop.Excel;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //OpenFileDialog ofd = new OpenFileDialog();
            //ofd.Filter = "excel (*.xlsx)|*.xlsx";
            //if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            //{
            //    label1.Text = ofd.FileName;
            //}

            string path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            label1.Text =  path+ "\\ .xlsx";
            
            string filename = label1.Text;


            Excel.Application app = new Excel.Application(); app.Visible = true;
            Excel.Workbook wbSource = app.Workbooks.Open(Filename: filename, ReadOnly: true);
            Excel.Worksheet shtSource = null;
            
            Excel.Workbook wbDest = null;
            //Excel.Worksheet shtDest = null;
            string pathDest = path + "\\A";


            List ls = new List();
            for (int i = 1; i <= wbSource.Worksheets.Count; i++)
            {
                shtSource = wbSource.Worksheets[i];
                if (!shtSource.Name.Equals("Sheet1"))
                {
                    wbDest = app.Workbooks.Add();
                    shtSource.Copy(Before: wbDest.Worksheets["Sheet1"]);
                    wbDest.SaveAs(Filename: pathDest + "\\" + shtSource.Name);
                    wbDest.Close();
                }
                
                ls.Add(shtSource.Name);


            }
            string msg = string.Join(Environment.NewLine,ls.ToArray());


            app.Quit();

            MessageBox.Show(msg);
        }
    }
}

좋은 웹페이지 즐겨찾기