我从这个问题中使用:http://support.microsoft.com/kb/302084从Visual C#导出到Excel,我没有任何问题。
要设置单元格边框,请使用以下代码:
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
oSheet.get_Range("A2", "J2").Borders.LineStyle = true;
以上的代码运作良好。
但现在我只想为奇数行设置单元格边框。
因此我想使用循环,就像我在下面定义的那样:
for(i=1,i<=6,i++)
{
oSheet.get_Range( , ).Borders.LineStyle = true; // only for odd rows.
}
但我不知道我必须如何更改上面的语法,以便在每个循环中根据变量进行更改。
答案 0 :(得分:0)
C#DataGridView导出到Excel:
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT * FROM Authors";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Authors_table");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";
}
private void button2_Click(object sender, EventArgs e)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
Int16 i, j;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
for (i = 0; i <= dataGridView1.RowCount - 2; i++)
{
for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
{
xlWorkSheet.Cells[i + 1, j + 1] = dataGridView1[j, i].Value.ToString();
}
}
xlWorkBook.SaveAs(@"c:\csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
将数据库导出到Excel文件
http://csharp.net-informations.com/excel/csharp-excel-export.htm
答案 1 :(得分:0)
正如我在评论中提到的:你只需要检查除以2的余数就可以找到奇数行或偶数行。
要仅为奇数行添加边框线样式(即第一行,第三行,第五行等),应该执行以下代码:
for(i=1,i<=6,i++)
{
if ((i % 2) == 1)
{
oSheet.get_Range( , ).Borders.LineStyle = true; // only for odd rows.
}
}
答案 2 :(得分:0)
要获取所有其他行,您可以使用步骤2重写for循环:
for (int i = 1; i <= 6; i+=2) // only for odd rows.
{
string c1 = "A" + i.ToString();
string c2 = "J" + i.ToString();
oSheet.get_Range(c1, c2).Borders.LineStyle = true;
}