c# - 文本到 Excel 中的列

标签 c# .net excel

我有一个包含单列和多行的 Excel 工作表,例如:

000500114673HY340216-00       CT TAPING WORK DTYPE-OSKF 245 TWB.T H/C 37990110000250000100

我正在尝试通过我的 C# 代码创建一个新的 Excel 文件,但没有得到想要的结果。在我的新 Excel 文件中,我需要六列,每列分配一个特定的范围,比如第一列 12,第二列 20 等等(也包括空格)。我使用了文本到列的方法,但我无法将其解析为固定宽度。我的代码示例是:

xlAppNew = new Application();
xlAppNew.DisplayAlerts = true;
workbooks = xlAppNew.Workbooks;                   
workbook = workbooks.Open(@filepath, 0, true, 1, "", "", true,
           Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t",
           false, false, 0, true, 1, 0);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.get_Item(1);        
((Range)xlAppNew.Cells[1, 1]).EntireColumn.TextToColumns(Type.Missing,
           Microsoft.Office.Interop.Excel.XlTextParsingType.xlFixedWidth,
           Microsoft.Office.Interop.Excel.XlTextQualifier.xlTextQualifierNone,
           Type.Missing, Type.Missing, Type.Missing, true, Type.Missing,
           Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
           Type.Missing);

我认为问题在于倒数第四个参数,我无法正确提供的 fieldinfo 对象,我也使用了数组对象,但它产生了错误。我从这个问题 4945621 得到了帮助。但是那里没有提供确切的解决方案。

最佳答案

实际上我要做的是先将 DAT 文件转换为 Excel,然后通过我的 C# 代码将其分成固定数量的列。因此,在我的第一步中,我所做的是将 DAT 文件转换为具有单列和给定行数的 Excel 文件作为我的临时 Excel 文件。

                xlAppNew1 = new Application();
                xlAppNew1.DisplayAlerts = true;
                workbooks1 = xlAppNew1.Workbooks;
                workbook1 = workbooks1.Open(@filepath, 0, true, 1, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
                xlAppNew1.ActiveWorkbook.SaveAs(@filepathNew, -4143, "", "", false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
                missing, missing, missing, missing, missing);

现在确保关闭您创建的 COM 对象的所有实例,否则会产生很多问题。其次,在另一个函数中,我打开了我的临时 Excel 文件,以及数据集中的所有数据,然后使用借助 Range 对象和以下方法:

     range = range.get_Resize(range.Rows.Count, 9);           
     string[,] saRet = new string[range.Rows.Count, 9];         
     range.set_Value(Missing.Value, saRet);

整个代码是这样的:

                xlAppNew = new Application();
                xlAppNew.DisplayAlerts = true;
                workbooks = xlAppNew.Workbooks;
                workbook = workbooks.Open(@filepathnew, 0, true, 1, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
                xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.get_Item(1);                    
                if (getExtension.ToLower() == ".xls")
                    connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath_second + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1;\"";

                else
                    connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath_second + ";Extended Properties=Excel 12.0 Xml;HDR=Yes;IMEX=1;";

                OleDbConnection con = new OleDbConnection(connString);

                con.Open();
                System.Data.DataTable dtSheet = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                string tname = dtSheet.Rows[0]["TABLE_NAME"].ToString();                    
                OleDbDataAdapter ad = new OleDbDataAdapter(@"Select * FROM [" + tname + "];", con);
                DataSet dset = new DataSet();
                ad.Fill(dset);
                range = xlWorkSheet.UsedRange;
                range = range.get_Resize(range.Rows.Count, 9);
                //Create an array.
                string[,] saRet = new string[range.Rows.Count, 9];
                //Fill the array.
                for (int iRow = 0; iRow < range.Rows.Count - 1; iRow++)
                {
                    for (int iCol = 0; iCol < 9; iCol++)
                    {
                        switch (iCol)
                        {
                            case 0:
                                saRet[iRow, iCol] = dset.Tables[0].Rows[iRow][0].ToString().Substring(3, 9);//iRow.ToString() + "|" + iCol.ToString();
                                break;
                            case 1:
                                saRet[iRow, iCol] = dset.Tables[0].Rows[iRow][0].ToString().Substring(12, 4);
                                break;
                            case 2:
                                saRet[iRow, iCol] = dset.Tables[0].Rows[iRow][0].ToString().Substring(16, 18);
                                break;
                            case 3:
                                saRet[iRow, iCol] = dset.Tables[0].Rows[iRow][0].ToString().Substring(34, 8);
                                break;
                            case 4:
                                saRet[iRow, iCol] = dset.Tables[0].Rows[iRow][0].ToString().Substring(42, 4);
                                break;
                            case 5:
                                saRet[iRow, iCol] = dset.Tables[0].Rows[iRow][0].ToString().Substring(46, 18);
                                break;
                            case 6:
                                saRet[iRow, iCol] = dset.Tables[0].Rows[iRow][0].ToString().Substring(64, 40);
                                break;
                            case 7:
                                saRet[iRow, iCol] = dset.Tables[0].Rows[iRow][0].ToString().Substring(104, 3);
                                break;
                            case 8:
                                saRet[iRow, iCol] = dset.Tables[0].Rows[iRow][0].ToString().Substring(107, 5);
                                break;

                        }

                    }
                }

                //Set the range value to the array.
                range.set_Value(Missing.Value, saRet);
                FieldInfo myf = typeof(MyNewService).GetField("saRet");//Fieldinfo object is also an important part
                //**********************
                ((Range)xlAppNew.Cells[1, 1]).EntireColumn.TextToColumns(Type.Missing, Microsoft.Office.Interop.Excel.XlTextParsingType.xlFixedWidth, Microsoft.Office.Interop.Excel.XlTextQualifier.xlTextQualifierNone, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, myf, Type.Missing, Type.Missing, Type.Missing);
                xlAppNew.ActiveWorkbook.SaveAs(@temp_path, -4143, "", "", false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);

希望它能帮助其他人节省时间。谢谢。

关于c# - 文本到 Excel 中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16768084/

相关文章:

sql - 使用 SQL 脚本在 SQL Server 中导入 DBF 文件

c# - 更好的 PropertyChanged 和 PropertyChanging 事件处理

c# - 一些 Excel 单元格保持未填充状态,使用 C#

Ruby/Watir - 从数组格式化打印

c# - 使用记事本进行 ASP.NET MVC 开发?

c# - XmlDocument 保存使文件保持打开状态

c# - 准备命令定义时出错。有关详细信息,请参阅内部异常

vba - 确定单元格是否包含数据验证

c# - .net 中的测试驱动开发和单元测试

c# - 如何更改 XML 父标签