简体   繁体   English

将datagridview数据导出到excel [excel文件应该是只读的]

[英]exporting datagridview data to excel [excel file should read only]

I want to export data from datagrid to excel file with below code I am exporting the data to excel but Iwant excel file of readonly which I am not getting with below code: 我想使用以下代码将数据从datagrid导出到excel文件中,我正在将数据导出到excel,但是我却无法使用下面的代码来获得只读的excel文件:

Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;

app.Visible = true;

worksheet = workbook.ActiveSheet;
for (int i = 1; i < dg1.Columns.Count + 1; i++)
{
    worksheet.Cells[1, i] = dg1.Columns[i - 1].HeaderText;
}
for (int i = 0; i < dg1.Rows.Count - 1; i++)
{
    for (int j = 0; j < dg1.Columns.Count; j++)
    {
        if (dg1.Rows[i].Cells[j].Value != null)
        {
            worksheet.Cells[i + 2, j + 1] = dg1.Rows[i].Cells[j].Value.ToString();
        }
        else
        {
            worksheet.Cells[i + 2, j + 1] = "";
        }

    }
    worksheet.Columns.AutoFit(); 
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Missing.Value);
Microsoft.Office.Interop.Excel._Worksheet worksheet = workbook.ActiveSheet;
worksheet = workbook.ActiveSheet;

//app.Visible = true;

//getting all the columns from datagrid
for (int i = 1; i < dg1.Columns.Count + 1; i++)
{
    worksheet.Cells[1, i] = dg1.Columns[i - 1].HeaderText;
}
//getting row collection
for (int i = 0; i < dg1.Rows.Count - 1; i++)
{
    for (int j = 0; j < dg1.Columns.Count; j++)
        {
            if (dg1.Rows[i].Cells[j].Value != null)
            {
                worksheet.Cells[i + 2, j + 1] = dg1.Rows[i].Cells[j].Value.ToString();
            }
            else
            {
                worksheet.Cells[i + 2, j + 1] = "";
            }
            worksheet.Columns.AutoFit();                                        
        }
}

//to make the excel sheet readonly
((Excel.Worksheet)app.ActiveWorkbook.Sheets[1]).EnableSelection = Excel.XlEnableSelection.xlUnlockedCells;
((Excel.Worksheet)app.ActiveWorkbook.Sheets[1]).Protect(Password: protectionpasswprd, AllowFormattingCells: false);
app.ActiveWorkbook.SaveCopyAs("D:\\a.xls");
app.ActiveWorkbook.Saved = true;
app.Quit();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM