在格式化模板中将csv转换为xls时,为什么第一张表格未格式化?

问题描述 投票:0回答:1

在VS 2017中构建一个读取CSV文件并使用c#将其转换为xls的应用程序。

我正在使用CsvHelper和Microsoft.Office.Interop.Excel来完成此任务。

应用程序可以以Windows窗体的形式读取CSV文件,让程序设置模板并将正确单元格中的所有值插入到该格式化模板中无论使用哪个文件而创建的第一页都未格式化并插入在未格式化的Excel页面中。

我试过了:

  1. 更改“Workbook.Sheets.Add”的参数
  2. 在逻辑中哪里添加了工作表
  3. 更改SaveAs函数中的参数
  4. 将各种指数从1改为0,反之亦然

我是使用(Interop.Excel)命名空间的新手,并且花了很多时间在MS网页上阅读DOCS但我仍然无法解决这个问题。

以下是我将页面添加到工作簿的方式:

if (!backgroundWorker.CancellationPending)
                        {
                            backgroundWorker.ReportProgress(index++ * 100 / pageCount);
                            Thread.Sleep(delay);
                            wb.Sheets.Add(missing,After:wb.Sheets[wb.Sheets.Count],Count:missing,Type:template);
                            Worksheet ws = (Worksheet)wb.Sheets[wb.Sheets.Count];
                        }

以下是我保存页面的方法:

wb.SaveAs(fileName, XlFileFormat.xlWorkbookDefault, missing, missing, true, false, XlSaveAsAccessMode.xlNoChange,
                        XlSaveConflictResolution.xlLocalSessionChanges,
                        missing, missing);
                    excel.Quit();

以下是整个方法的参考:

namespace csvReader
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        struct DataParameter
        {
            public List<material> materialList;
            public List<material> smallMats;
            public Workbook wbData;
            public string Filename { get; set; }
            public int Delay;
        }

        DataParameter _inputParameter;
private void btnWrite_Click(object sender, EventArgs e)
        {
            if (backgroundWorker.IsBusy)
                return;
            using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "Excel Workbook|*.xls" })
            {
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    _inputParameter.Filename = sfd.FileName;
                    _inputParameter.materialList = materialBindingSource2.DataSource as List<material>;
                    _inputParameter.Delay = 100;
                    progressBar.Minimum = 0;
                    progressBar.Value = 0;


                    backgroundWorker.RunWorkerAsync(_inputParameter);
                }
            }
        }
 private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            object missing = Type.Missing;
            List<material> list = ((DataParameter)e.Argument).materialList;
            List<material> cellM = ((DataParameter)e.Argument).smallMats;
            string fileName = ((DataParameter)e.Argument).Filename;
            int pageCount = 1;
            int process = list.Count;
            int setRows = 19;
            int delay = 100;

            if (list.Count > setRows)
            {
                pageCount = process / setRows;
            }
            Microsoft.Office.Interop.Excel.Application excel = new 
    Microsoft.Office.Interop.Excel.Application();
            string template = "(mytemplatefilepath)";
            Workbook wb = ((DataParameter)e.Argument).wbData;
            wb = excel.Workbooks.Add();
            excel.Visible = false;

            int index = 1;

            try
            {
                for (int i = 1; i < pageCount; i++)
                {
                    if (!backgroundWorker.CancellationPending)
                    {
                        backgroundWorker.ReportProgress(index++ * 100 / pageCount);
                        Thread.Sleep(delay);
                        wb.Sheets.Add(missing,After:wb.Sheets[wb.Sheets.Count],Count:missing,Type:template);
                        Worksheet ws = (Worksheet)wb.Sheets[wb.Sheets.Count];
                    }
                }

                int range = 1;
                int sheetIndex = 1;


                foreach (Worksheet w in wb.Sheets)
                {                    
                    w.Name = "Sheet" + sheetIndex++;
                    //w.Cells["L", 3] = tbSpecial.Text;
                    cellM = list.GetRange(range, 19);
                    int startCell = 7;
                    foreach (material m in cellM)
                    {
                        if (!backgroundWorker.CancellationPending)
                        {

                            backgroundWorker.ReportProgress(index++ * 100 / process);
                            Thread.Sleep(delay);
                            Microsoft.Office.Interop.Excel.Range newInput = w.get_Range("C" + startCell, "L" + startCell) as Microsoft.Office.Interop.Excel.Range;                           
                            w.Cells[startCell, 2] = m.Qty.ToString();
                            w.Cells[startCell, 3] = m.Section.ToString();
                            w.Cells[startCell, 4] = m.Length.ToString();
                            w.Cells[startCell, 5] = m.Camber.ToString();
                            w.Cells[startCell, 6] = m.Ends.ToString();
                            w.Cells[startCell, 7] = m.Grade.ToString();
                            w.Cells[startCell, 8] = m.Seq.ToString();
                            w.Cells[startCell, 9] = m.Member.ToString();
                            //w.Cells["L", 3] ="700";
                            startCell++;
                        }
                    }
                    range = range + 19;
                }
                wb.SaveAs(fileName, XlFileFormat.xlWorkbookDefault, missing, missing, true, false, XlSaveAsAccessMode.xlNoChange,
                    XlSaveConflictResolution.xlLocalSessionChanges,
                    missing, missing);
                excel.Quit();
            }
            catch (Exception ex)
            {
                backgroundWorker.CancelAsync();
                MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

这是203页数据集的第一页

https://imgur.com/t6dd2ip

其他202页显示如此

https://imgur.com/jMuNMeb

我觉得这是语法错误我在某处。虽然很容易填写一个excel页面,但我宁愿使用我正在使用的技术完成100%的这项工作。

c# excel csv interop xls
1个回答
1
投票

第一张工作表没有模板布局的原因是,如果'i = 0'炸弹是默认情况下,在使用Workbooks.Add()实例化工作簿时,会添加一个新的工作表。此工作表不会被格式化,但可以在Add方法的括号中添加模板,以便为该第一个工作表提供该格式。

string template = "C:/whereEverMyTemplateIs/template"
 wb = excel.Workbooks.Add(template);

然后记住它已添加并根据需要制作更多

for (int i = 1; i < pageCount; i++)
                {
                    if (!backgroundWorker.CancellationPending)
                    {
                        backgroundWorker.ReportProgress(index++ * 100 / pageCount);
                        Thread.Sleep(delay);
                        wb.Sheets.Add(missing,After:wb.Sheets[wb.Sheets.Count],Count:missing,
Type:template);
                        //Worksheet ws = (Worksheet)wb.Sheets[wb.Sheets.Count];
                    }
                }
© www.soinside.com 2019 - 2024. All rights reserved.