博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Excel:合并某一列
阅读量:5319 次
发布时间:2019-06-14

本文共 1709 字,大约阅读时间需要 5 分钟。

//创建一个Excel.Application的新进程

Microsoft.Office.Interop.Excel.Application app = new Application();
if (app == null) return;
app.Visible = false;
app.UserControl = true;
Workbooks workbooks = app.Workbooks;
_Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);//这里的Add方法里的参数就相当于继承了一个空模板(暂这样理解吧)
Sheets sheets = workbook.Worksheets;
_Worksheet worksheet = (_Worksheet)sheets.get_Item(1);
if (worksheet == null) return;

DataSet ds = Convert_StringToDataSet(str);

System.Data.DataTable dt = ds.Tables[0];
string bidName = "";
int projNum = 0;
for (int i = 0; i < dt.Rows.Count; i++)
{
    projNum++;
    bidName = dt.Rows[i]["BigFactorClassName"].ToString();
    worksheet.Cells[1 + i, 1] = i + 1;
    worksheet.Cells[1 + i, 3] = dt.Rows[i]["SmallFactorClassName"];
    worksheet.Cells[1 + i, 4] = dt.Rows[i]["FactorClassName"];
    if (i == 0)//如果是第一行,就直接写了
    {
        worksheet.Cells[1 + i, 2] = dt.Rows[i]["BigFactorClassName"];
    }
    else if (bidName == dt.Rows[i - 1]["BigFactorClassName"].ToString())//此行与上一行时行比较,如果相等就不写值
    {
        worksheet.get_Range(worksheet.Cells[i + 1, 2], worksheet.Cells[i, 2]).Merge(Type.Missing);
    }
    else
    {
        worksheet.Cells[1 + i, 2] = dt.Rows[i]["BigFactorClassName"];
    }
}

worksheet.Name = "导出Excel测试1";

string tick = DateTime.Now.Ticks.ToString();
string save_path = "C:\\Users\\Administrator\\Desktop\\" + tick + ".xls";

workbook.SaveAs(save_path, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

Response.Write("<script>alert('导出成功!')</script>");

转载于:https://www.cnblogs.com/pnljs/archive/2012/02/22/2363132.html

你可能感兴趣的文章