我之前有类似的问题,但我仍然对实际解决方案感到冷淡。我将动态文本框中的文本行发送到Excel,此信息来自数据库。在我发送的行中" txtProductNameBundle"有时,产品描述"(" txtProductDesc")行必须拆分,并且需要在" txtProductNameBundle"下进行。在Excel中,它可以是1行或最多6个。我的for循环成功地将所有行(没有产品描述)发送到我需要的地方。这是问题,我知道如何执行"拆分字符串"使用" txtProductDesc"因为这个文本可以相当长,甚至可以发送到Excel,但我对如何添加循环以将其放在"产品名称"之后无能为力。 Excel工作表是一个模板,因此必须为要发送的信息行插入行。
int StartBundleRow = 11; // row 11 is where I start to insert the dynamic controls
string rowIndent = " "; // adds spaces to the beginning of the text
string DescriptionSplit = frmProposal.ProdDesc.Text;
for (int BndlRow = 0; BndlRow < bundleRows; BndlRow++)
{
worksheet.Rows[StartBundleRow].Insert();
worksheet.Rows[StartBundleRow].Font.Size = 14; //********Excel formatting*********
worksheet.Cells[StartBundleRow, "E"].Font.Bold = true;
worksheet.Rows[StartBundleRow].Interior.Color = ColorTranslator.ToOle(Color.White);
worksheet.Columns["A"].Interior.Color = ColorTranslator.ToOle((Color)cc.ConvertFromString("#808080"));
worksheet.Columns["J:XFD"].Interior.Color = ColorTranslator.ToOle((Color)cc.ConvertFromString("#808080"));
worksheet.Rows[StartBundleRow].HorizontalAlignment = XlHAlign.xlHAlignLeft;
worksheet.Cells[StartBundleRow, "C"].Interior.Color = ColorTranslator.ToOle((Color)cc.ConvertFromString("#49176D"));
worksheet.Cells[StartBundleRow, "D"].value = srcBundlePanel.Controls["txtQtyBundle" + BndlRow].Text;
//(product name below)
worksheet.Cells[StartBundleRow, "E"].value = srcBundlePanel.Controls["txtProductNameBundle" + BndlRow].Text;
//(this is where I need to insert the split string of product description)
worksheet.Cells[StartBundleRow, "F"].value = srcBundlePanel.Controls["txtListPriceBundle" + BndlRow].Text;
worksheet.Cells[StartBundleRow, "G"].value = srcBundlePanel.Controls["txtMaxDiscountBundle" + BndlRow].Text;
worksheet.Cells[StartBundleRow++,"H"].value = srcBundlePanel.Controls["txtProposedPriceBundle" + BndlRow].Text;
}
** BELOW IS MY SAMPLE STAND ALONE CODE FOR SPLITTING THE STRING INTO 3 ROWS **
worksheet.Cells[11, "E"].Value = rowIndent + DescriptionSplit.Substring(0, DescriptionSplit.IndexOf("|")).Trim();
worksheet.Cells[12, "E"].Value = rowIndent + DescriptionSplit.Substring(DescriptionSplit.IndexOf("|") + 1,
DescriptionSplit.IndexOf("|")).Trim();
worksheet.Cells[13, "E"].Value = rowIndent + DescriptionSplit.Substring(DescriptionSplit.LastIndexOf("|") + 1,
DescriptionSplit.Length - DescriptionSplit.LastIndexOf("|") - 1).Trim();
答案 0 :(得分:1)
只要每个部分由管道字符分隔,就可以简化描述字符串的拆分。
string[] descriptionParts = DescriptionSplit.Split('|');
要插入行,您可以使用简单的for循环:
for(int i = 0; i < descriptionParts.Length; i++)
{
worksheet.Cells[StartBundleRow + i, "E"].Value =
rowIndent + descriptionParts[i].Trim();
}
您可能还想用下面的代码替换最后一行,根据描述使用的行数调整下一个包的行偏移量:
worksheet.Cells[StartBundleRow,"H"].value =
srcBundlePanel.Controls["txtProposedPriceBundle" + BndlRow].Text;
StartBundleRow += descriptionParts.Length;