Excel将一列拆分为C#中的多列 [英] Excel split one column into multiple columns in C#

查看:65
本文介绍了Excel将一列拆分为C#中的多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助无法获得如何Excel将一列拆分为c#中的多列。



我想知道是否有人可以建议如何拆分字符串将逗号分隔的值分隔为多个列。我一直试图解决这个问题,但一直很难找到一个好的解决方案。 (也在线查看,似乎有几个接近但不一定适合我所需要的)



假设我有一个工作表,称之为示例,例如,并在工作表中有多行下面的以下字符串,但都在A列中。



please help not able to get how to Excel Split one column into multiple columns in c#.

I was wondering if anybody can kindly advise how to split a string with comma-separated values into multiple columns. I have been trying to figure this out but have been having a hard time finding a good solution. (also checked online, seems several that comes close but not necessarily fit what I exactly need)

Let's say I have a worksheet, call it "example", for instance, and in the worksheet has the following strings under multiple rows but all in column "A".

20120112,aaa,bbb,ccc,3432 
20120113,aaa,bbb,ccc
20120113,ddd,bb,ccc,ddd,eee,fff,ggg,hhhh 
20120132,aaa,bbb,ccc
20120112,aaa,bbb,ccc 
20120112,xxx,bbb,ggg,ggg,333
20120112,aaa,bbb,ccc 
20120112,abbd,bbb,ccc





如何创建一个将上面分成多列的宏?



请查找下面的代码将从datatable获取数据并将其存储到内存流并导出到excel。现在我必须将第一列拆分为多列请帮助





How can I create a macro that will split the above into multiple columns ?

Please find the below code which will get data from datatable and store it to memory stream and export to excel. Now i have to split first column to multiple columns please help

DataSet ds = new DataSet();
ds.Tables.Add(dt);    \\loading datatable "dt" into dataset

var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(ToCSV(dt));
                MemoryStream ms = new MemoryStream(bytes);

               using (var fs = new FileStream(_path, FileMode.Create, FileAccess.Write))
               {
                   ms.WriteTo(fs);
               }


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

               excel.Workbooks.Open(_path, ReadOnly: true);

   public string ToCSV(DataTable table)
        {
            var result = new StringBuilder();
            for (int i = 0; i < table.Columns.Count; i++)
            {
                result.Append(table.Columns[i].ColumnName);
                result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
            }

            foreach (DataRow row in table.Rows)
            {
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    result.Append(row[i].ToString());
                    result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
                }
            }

            return result.ToString();
        }

推荐答案

伪代码:

Pseudo code:
for each row
    get a string to a variable
    use regex to split the string
    store the list items in matching cells


using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        Excel.Range range;

protected void Page_Load(object sender, EventArgs e)
       {

           string str;
           int rCnt = 0;
           int cCnt = 0;

           int maxLength = 0;
           int PreMaxLength = 0;

           List<string[]> arrString = new List<string[]>();

           xlApp = new Excel.Application();
           xlWorkBook = xlApp.Workbooks.Open(@"UseFilepath", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
           xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
           range = xlWorkSheet.UsedRange;

           for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
           {
               for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
               {
                   str = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2;
                   arrString.Add(str.Split(',').ToArray());
                   PreMaxLength = str.Split(',').ToArray().Length;
                   if (maxLength < PreMaxLength)
                   {
                       maxLength = PreMaxLength;
                   }
               }
           }

           xlWorkBook.Close(true, null, null);
           xlApp.Quit();

           releaseObject(xlWorkSheet);
           releaseObject(xlWorkBook);
           releaseObject(xlApp);

           CreateExcel(arrString, maxLength);

       }
       private void releaseObject(object obj)
       {
           try
           {
               System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
               obj = null;
           }
           catch (Exception ex)
           {
               obj = null;

           }
           finally
           {
               GC.Collect();
           }
       }

       private void CreateExcel(List<string[]> arrString, int Length)
       {
           try
           {
               xlApp = new Excel.Application();
               xlApp.Visible = false;
               xlApp.DisplayAlerts = false;
               xlWorkBook = xlApp.Workbooks.Add(Type.Missing);


               xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.ActiveSheet;
               xlWorkSheet.Name = "Test";
               xlWorkSheet.Cells.Font.Size = 15;

                   int rowcount = 1;
                   int i = 1;
                   foreach (string[] x in arrString)
                   {
                       rowcount += 1;
                       range = xlWorkSheet.Range[xlWorkSheet.Cells[rowcount, 1], xlWorkSheet.Cells[rowcount, Length]];
                       foreach (string s in x)
                       {
                           xlWorkSheet.Cells[rowcount, i] = s.ToString();
                           i++;
                       }
                       i = 1;
                   }

                   range.EntireColumn.AutoFit();
                   Microsoft.Office.Interop.Excel.Borders border = range.Borders;
                   border.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                   border.Weight = 2d;
                   xlWorkBook.SaveAs(@"C:\Test1.xlsx"); 
                   xlWorkBook.Close();
                   xlApp.Quit();

           }
           catch (Exception ex)
           {


           }
           finally
           {

           }
       }


这篇关于Excel将一列拆分为C#中的多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆